如何在Python中复制文件?
如何在Python中复制文件?
shutil
模块提供了一些高级文件操作功能,支持文件 复制
和 移除
。
根据您的使用情况,请参考以下表格。
功能 | 使用 文件对象 |
保留文件 元数据 |
保留 权限 |
支持 目录目标 |
---|---|---|---|---|
shutil.copyfileobj | ✔ | ⅹ | ⅹ | ⅹ |
shutil.copyfile | ⅹ | ⅹ | ⅹ | ⅹ |
shutil.copy2 | ✔ | ✔ | ✔ | ✔ |
shutil.copy | ⅹ | ⅹ | ✔ | ✔ |
从Python 3.5开始,您可以对小文件(即文本文件、小型JPEG图像)执行以下操作:
from pathlib import Path
source = Path('../path/to/my/file.txt')
destination = Path('../path/where/i/want/to/store/it.txt')
destination.write_bytes(source.read_bytes())
write_bytes
会覆盖目标位置上的任何内容。
你可以使用 os.system('cp 由程序生成的文件名 /其他目录/')
。
或者像我这样做:
os.system('cp '+ rawfile + ' rawdata.dat')
这里的 rawfile
是在程序中我所生成的名称。
这是仅适用于Linux系统的解决方案。
shutil
,subprocess.run()
(不使用shell=True
!)也是比os.system()
更好的选择。 - maxschlepzigsubprocess.run()
正如 @maxschlepzig 建议的那样,在调用外部程序时是一个很大的进步。然而,为了灵活性和安全性,请使用 ['cp', rawfile, 'rawdata.dat']
形式来传递命令行。 (但是,对于复制操作,建议使用 shutil
和相关工具,而不是调用外部程序。) - Marcel Waldvogel使用
open(destination, 'wb').write(open(source, 'rb').read())
以读模式打开源文件,以写模式写入目标文件。
open(...)
都没有调用.close()
,不是吗? - luckydonaldwith
(如上面的示例)而不是更复杂的方法。在原始文件上使用read()
会将整个文件读入内存,这可能太大了。使用像shutil
中的标准函数,这样您和其他参与代码的人就不需要担心特殊情况。https://docs.python.org/3/library/io.html#io.BufferedReader - Marcel Waldvogel对于大文件,我逐行读取文件并将每一行读入数组中。然后,一旦数组达到一定大小,就将其附加到新文件中。
for line in open("file.txt", "r"):
list.append(line)
if len(list) == 1000000:
output.writelines(list)
del list[:]
for l in open('file.txt','r'): output.write(l)
应该可以工作;只需根据您的需要设置输出流缓冲区即可。或者您可以通过循环尝试来按字节进行操作 output.write(read(n)); output.flush()
,其中 n
是您想要一次写入的字节数。这两种方法都没有检查条件,这是一个优点。 - ownswritelines()
相对于 write()
显示出稍微更好的性能,因为我们不会浪费时间不断打开新的文件流,而是将新行作为一个大的字节流写入。 - rassa45shutil.copyfile()
**,在3.8上已经进一步改进以使用本机操作系统支持的快速文件复制。它很容易比这个答案所需的时间少一半。 - Martijn Pieters使用 subprocess.call
来复制文件
from subprocess import call
call("cp -p <file> <file>", shell=True)
如果您已经看到了这里,答案是您需要完整的路径和文件名。
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
from os import path, makedirs
from shutil import copyfile
makedirs(path.dirname(path.abspath(destination_path)), exist_ok=True)
copyfile(source_path, destination_path)
正如接受的答案所述,这些行会覆盖目标路径下存在的任何文件,因此有时在此代码块之前添加if not path.exists(destination_path):
也可能很有用。