有没有办法等待 os.remove() 完成?我有一个脚本,每天制作一些 png 图片并先删除旧图片,所以制作的图片实际上是旧图片的更新。
问题是 - 我猜 - os.remove() 没有足够的时间来完成,因为正在创建的文件与正在删除的文件完全相同。但是,如果我在 os.remove() 之后放置一个 time.sleep(5),它就会起作用。
代码是这样的
...some imports
for root, dirs, files in os.walk(trgt_folder):
[os.remove(os.path.join(root, file)) for file in files if 'png' in file]
make_and_save_newpics(trgt_folder)
最佳答案
如果你覆盖同一个文件,我会推荐一个更好的解决方案,而不是给一个 time.sleep(5),为什么不检查文件是否存在,然后再次删除文件保存:
import os
# put this check before file save operation
if os.path.isfile(filepath):
os.remove(os.path.join(root, file))
# save new pic after this
make_and_save_newpics(trgt_folder)
如果时间有限,会有更好的方法,time.sleep(5) 不是一个好方法
关于python - 有没有办法等待 os.remove() 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47590779/