Python while loop to check if file exists

旧街凉风 提交于 2019-12-11 13:22:37

问题


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.

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!


回答1:


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)

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




回答2:


Assuming that you're on Linux:

If you really want to avoid any kind of looping to find if the file exists AND you're sure that it will be created at some point and you know the directory where it will be created, you can track changes to the parent directory using pynotify. It will notify you when something changes and you can detect if it's the file that you need being created.

Depending on your needs it might be more trouble than it's worth, though, in which case I suggest a small polling function like Kyle's solution.



来源:https://stackoverflow.com/questions/14404661/python-while-loop-to-check-if-file-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!