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?
有什么想法吗?
3 个解决方案
#1
48
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 KeyboardInterruption
exception if the file is never created. You should also check if the path is a file after, to avoid some unwanted exceptions.
每次检查后等待一段时间,然后在路径存在时读取文件。如果永远不会创建该文件,则可以使用KeyboardInterruption异常停止该脚本。您还应检查路径是否为文件后,以避免一些不必要的异常。
#2
3
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
#3
0
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")
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")
#1
48
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 KeyboardInterruption
exception if the file is never created. You should also check if the path is a file after, to avoid some unwanted exceptions.
每次检查后等待一段时间,然后在路径存在时读取文件。如果永远不会创建该文件,则可以使用KeyboardInterruption异常停止该脚本。您还应检查路径是否为文件后,以避免一些不必要的异常。
#2
3
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
#3
0
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")
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")