Python while循环检查文件是否存在 [英] Python while loop to check if file exists

查看:585
本文介绍了Python while循环检查文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我正在编码一些看起来真的很奇怪的东西,而且我无法从逻辑上弄清楚如何实现它,而且我觉得如果这样做,它将使CPU融化-所以我认为我会问真正了解的人。

Hey guys I'm coding something that seems really weird to me, and I can't logically figure out how to implement it, and I feel like if I do it'll be cpu melting - so I figure I'd ask people who really know.

我要做的是检查文件是否存在,如果不存在,请执行操作,然后再次检查,直到文件存在,然后代码继续传递。我尝试了Google搜索,但收效甚微。感谢所有提供帮助的人!

What I want to do is check if a file exists, if it doesn't, perform an action, then check again, until the file exists and then the code passes on with that. I've tried Googling to little avail. Thanks to anyone who helps!

推荐答案

为简单起见,我将实现一个小的轮询功能,并设置一个安全超时时间:

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内置的轮询,因为它将跟踪/报告文件描述符的IO事件

I would also look into using Python built-in polling, as this will track/report I/O events for your file descriptor

这篇关于Python while循环检查文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆