检查并等待文件存在以进行读取

spe*_*zor 44 python

我需要等到文件创建然后读入.我有以下代码,但确定它不起作用:

import os.path
if os.path.isfile(file_path):
    read file in
else:
    wait
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

Max*_*ant 72

一个简单的实现可能是:

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)
Run Code Online (Sandbox Code Playgroud)

每次检查后等待一段时间,然后在路径存在时读取文件.KeyboardInterruption如果永远不会创建该文件,则可以停止该脚本.您还应检查路径是否为文件,以避免一些不必要的异常.

  • 如果我创建一个目录为`file_path`,该程序将等待无限时间:p (8认同)
  • @thefourtheye:这重要吗?如果在该路径上没有创建任何内容,程序也会永远等待。 (3认同)
  • @aim:你可以但我们应该保持答案简单(lees比10行没有任何变量)并让人们根据需要自定义它. (3认同)

SIM*_*SIM 10

一旦下载文件或创建了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")
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这样,因为永远等待是错误的。 (2认同)