【问题标题】:Copy a file, but don't overwrite, without TOCTTOU issues in Python复制文件,但不要覆盖,在 Python 中没有 TOCTTOU 问题
【发布时间】:2015-05-25 23:20:58
【问题描述】:

我知道如果我想在 Python 中复制一个文件但不覆盖目标,我可以使用如下代码:

if os.path.exists(dest):
    raise Exception("Destination file exists!")
else:
    shutil.copy2(src, dest)

但是在我打电话给os.path.exists 和我打电话给copy2 之间,世界的状态可能会发生变化。有没有更优选的复制而不覆盖的方法,大概如果目标已经存在,复制操作会引发异常?

【问题讨论】:

    标签: python race-condition shutil


    【解决方案1】:

    您可以使用较低级别的os.open 然后os.fdopen 来复制文件:

    import os
    import shutil
    
    # Open the file and raise an exception if it exists
    fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
    
    # Copy the file and automatically close files at the end
    with os.fdopen(fd) as f:
        with open(src_filename) as sf:
            shutil.copyfileobj(sf, f)
    

    【讨论】:

    • os.fdopen(fd) 也许?
    • 使用shutil.copyfileobj(sf, f)f.write(sf.read()) 更可取,因为它不会将整个文件读入内存
    • 谢谢你们!我做了这些改变。
    • 这当然可以,谢谢。两个注意事项:filename 是输入文件名;并且想要复制 shutil.copy2 行为的人会想要在最后运行 shutil.copystat (尽管这在问题中并不明确)
    猜你喜欢
    • 2015-04-05
    • 2011-05-12
    • 2012-07-20
    • 1970-01-01
    • 2018-04-25
    • 2013-01-23
    • 2013-05-20
    • 2013-03-08
    • 2023-01-27
    相关资源
    最近更新 更多