简体   繁体   English

如果文件不存在,请重新启动循环

[英]Restart the loop if file doesn't exist

At the beginning of a Python loop, I want the code to test if a certain file exists in the current folder, and if it doesn't, I want it to jump out and restart the loop with the next value. 在Python循环的开始,我希望代码测试当前文件夹中是否存在某个文件,如果不存在,则希望它跳出并使用下一个值重新开始循环。

I have done this before when trying to remove a file: 在尝试删除文件之前,我已经这样做了:

try:
    os.remove('file.txt')
except os.error:
    pass

Would I need to do something similar? 我需要做类似的事情吗? But instead of "pass", I would "continue"? 但是,我会“继续”而不是“通过”?

Obviously I am not trying to remove a file now, I just want to see if it exists. 显然,我现在不打算删除文件,我只想查看它是否存在。 Thank you! 谢谢!

Use 采用

os.path.exists()

for checking if your file exists. 用于检查文件是否存在。

You are better to just use the exception handler. 最好只使用异常处理程序。 If you check the file and then try to delete it, you may get an exception anyway if something else deletes the file just after you check 如果您检查文件然后尝试将其删除,则在检查后如果其他人删除了该文件,则仍然可能会出现异常。

for filename in filenames:
    try:
        os.remove(filename)
    except os.error:
        pass

checking for existance of the filename is done like this 这样检查文件名是否存在

for filename in filenames:
    if os.path.exists(filename):
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM