Python 检查并等待文件存在以读取它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21746750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:32:03  来源:igfitidea点击:

Check and wait until a file exists to read it

python

提问by speedyrazor

I need to wait until a file is created then read it in. I have the below code, but sure it does not work:

我需要等到一个文件被创建然后读入。我有下面的代码,但确定它不起作用:

import os.path
if os.path.isfile(file_path):
    read file in
else:
    wait

Any ideas please?

请问有什么想法吗?

采纳答案by Maxime Lorant

A simple implementation could be:

一个简单的实现可能是:

import os.path
import time

while not os.path.exists(file_path):
    time.sleep(1)

if os.path.isfile(file_path):
    # read file
else:
    raise ValueError("%s isn't a file!" % file_path)

You wait a certain amount of time after each check, and then read the file when the path exists. The script can be stopped with the KeyboardInterruptionexception if the file is never created. You should also check if the path is a file after, to avoid some unwanted exceptions.

每次检查后等待一定时间,然后在路径存在时读取文件。KeyboardInterruption如果从未创建文件,则可以停止脚本但有例外。您还应该检查路径是否是文件之后,以避免一些不需要的异常。

回答by Sakam24

import os
import time
file_path="AIMP2.lnk"
if  os.path.lexists(file_path):
    time.sleep(1)
    if os.path.isfile(file_path):
        fob=open(file_path,'r');
        read=fob.readlines();
        for i in read:
            print i
    else:
        print "Selected path is not file"
else:
    print "File not Found "+file_path

回答by Nori

This code can check download by file size.

此代码可以按文件大小检查下载。

import os, sys
import time

def getSize(filename):
    if os.path.isfile(filename): 
        st = os.stat(filename)
        return st.st_size
    else:
        return -1

def wait_download(file_path):
    current_size = getSize(file_path)
    print("File size")
    time.sleep(1)
    while current_size !=getSize(file_path) or getSize(file_path)==0:
        current_size =getSize(file_path)
        print("current_size:"+str(current_size))
        time.sleep(1)# wait download
    print("Downloaded")

回答by SIM

The following script will break as soon as the file is dowloaded or the file_path is created otherwise it will wait upto 10 seconds for the file to be downloaded or the file_path to be created before breaking.

一旦文件被下载或 file_path 被创建,以下脚本将立即中断,否则它将等待长达 10 秒的文件下载或 file_path 在中断前创建。

import os
import time

time_to_wait = 10
time_counter = 0
while not os.path.exists(file_path):
    time.sleep(1)
    time_counter += 1
    if time_counter > time_to_wait:break

print("done")