我会通过二进制复制损坏文本文件吗?

Will I damage a text file by binary copying it?

我想复制文件名中包含错误字符的 files/directories 树(当然是递归的)。因此,我打开文件,读取其内容,然后将它们转储到一个名称经过清理的新文件中。

如果文件的内容是文本,我在二进制模式下将它们 read() 写入 write(),是否有可能损坏内容?

for name in os.listdir(src_path):
    name = clean_name(name)
    src_full = os.sep.join((src_path, name))
    dst_full = os.sep.join((dst_path, name))
    ...
    if isfile(src_full):
        with open(dst_full, 'xb'): as dst_file:
            with open(src_full, 'rb')) as src_file:
               dst_file.write(src_file.read())

不,不可能损坏内容。只要您的硬件可以为您提供准确的内容,您就会一点一滴地阅读准确的内容。

可能发生的是您忘记复制整个文件元数据;例如,访问控制信息以及修改和创建日期丢失。

与其将整个文件读入内存,不如使用 shutil.copyfile() function to handle the file copy for you; it'll copy data across in blocks. Better still, use the shutil.copy() or shutil.copy2() 函数,它也会跨权限复制; copy2() 还会复制文件访问和创建时间。

这三个函数都以二进制模式打开文件;源用 'rb' 打开,目标用 'wb' 打开。如果您 必须 独占打开(模式 'xb'),您将需要自己打开文件对象(就像您已经做的那样)并使用 shutil.copyfileobj() to get the efficient file copy, followed either by a shutil.copymode() call (to replicate shutil.copy() and copy file permissions) or a shutil.copystat() call(以复制 shutil.copy2() 所做的。