如何在Python中复制文件?
当前回答
使用subprocess.call复制文件
from subprocess import call
call("cp -p <file> <file>", shell=True)
其他回答
使用subprocess.call复制文件
from subprocess import call
call("cp -p <file> <file>", shell=True)
Use
open(destination, 'wb').write(open(source, 'rb').read())
以读取模式打开源文件,以写入模式写入目标文件。
万一你走得这么远。答案是您需要整个路径和文件名
import os
shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))
Function | Copies metadata |
Copies permissions |
Uses file object | Destination may be directory |
---|---|---|---|---|
shutil.copy | No | Yes | No | Yes |
shutil.copyfile | No | No | No | No |
shutil.copy2 | Yes | Yes | No | Yes |
shutil.copyfileobj | No | No | Yes | No |
shutil有很多方法可以使用。其中之一是:
import shutil
shutil.copyfile(src, dst)
# 2nd option
shutil.copy(src, dst) # dst can be a folder; use shutil.copy2() to preserve timestamp
将名为src的文件的内容复制到名为dst的文件中。src和dst都需要是文件的整个文件名,包括路径。目标位置必须是可写的;否则,将引发IOError异常。如果dst已经存在,则将替换它。无法使用此功能复制字符或块设备和管道等特殊文件。对于copy,src和dst是作为strs给出的路径名。
另一个shutil方法是shutil.copy2()。它类似,但保留了更多的元数据(例如时间戳)。
如果使用os.path操作,请使用copy而不是copyfile。copyfile将只接受字符串。
推荐文章
- 使用beautifulsoup提取属性值
- 如何禁用标准错误流的日志记录?
- 用Matplotlib在Python中绘制时间
- 类中的Python装饰器
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- __FILE__宏显示完整路径
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代