如何创建一个while循环来检查文件是否存在? [英] How to create a while loop to check if a file exists?
本文介绍了如何创建一个while循环来检查文件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要做的是检查文件是否存在,如果不存在,请执行一个操作,然后再次检查,直到文件存在,然后代码继续执行其他操作.
What I want to do is to check if a file exists, and if it doesn't, perform an action, then check again, until the file exists and then the code continues on with other operations.
推荐答案
为简单起见,我将实现一个小的轮询功能,并为安全起见设置超时:
For simplicity, I would implement a small polling function, with a timeout for safety:
def open_file(path_to_file, attempts=0, timeout=5, sleep_int=5):
if attempts < timeout and os.path.exists(path_to_file) and os.path.isfile(path_to_file):
try:
file = open(path_to_file)
return file
except:
# perform an action
sleep(sleep_int)
open_file(path_to_file, attempts + 1)
我还将研究使用Python内置的轮询,因为这将跟踪/报告文件描述符的I/O事件
I would also look into using Python built-in polling, as this will track/report I/O events for your file descriptor
这篇关于如何创建一个while循环来检查文件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文