如何在Python中复制文件?
当前回答
Use
open(destination, 'wb').write(open(source, 'rb').read())
以读取模式打开源文件,以写入模式写入目标文件。
其他回答
从Python 3.5开始,您可以对小文件(例如:文本文件、小jpegs)执行以下操作:
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将覆盖目标位置的任何内容
复制文件是一个相对简单的操作,如下面的示例所示,但是您应该使用shutilstdlib模块。
def copyfileobj_example(source, dest, buffer_size=1024*1024):
"""
Copy a file from source to dest. source and dest
must be file-like objects, i.e. any object with a read or
write method, like for example StringIO.
"""
while True:
copy_buffer = source.read(buffer_size)
if not copy_buffer:
break
dest.write(copy_buffer)
如果要按文件名复制,可以执行以下操作:
def copyfile_example(source, dest):
# Beware, this example does not handle any edge cases!
with open(source, 'rb') as src, open(dest, 'wb') as dst:
copyfileobj_example(src, dst)
copy2(src,dst)通常比copyfile(src,gst)更有用,因为:
它允许dst是一个目录(而不是完整的目标文件名),在这种情况下,src的基本名称用于创建新文件;它在文件元数据中保留了原始的修改和访问信息(mtime和atime)(不过,这会带来一些开销)。
下面是一个简短的示例:
import shutil
shutil.copy2('/src/dir/file.ext', '/dst/dir/newname.ext') # complete target filename given
shutil.copy2('/src/file.ext', '/dst/dir') # target filename is /dst/dir/file.ext
您可以使用os.system('cp nameoflegatedbyprogram/otherdirectory/')。
或者就像我做的那样,
os.system('cp '+ rawfile + ' rawdata.dat')
其中rawfile是我在程序中生成的名称。
这是一个仅限Linux的解决方案。
您可以使用系统。
对于类Unix系统:
import os
copy_file = lambda src_file, dest: os.system(f"cp {src_file} {dest}")
copy_file("./file", "../new_dir/file")
推荐文章
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?