如何在 Python 中复制文件? [英] How do I copy a file in Python?
本文介绍了如何在 Python 中复制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在 Python 中复制文件?
How do I copy a file in Python?
我在 os
.
I couldn't find anything under os
.
推荐答案
shutil
有很多方法可以使用.其中之一是:
shutil
has many methods you can use. One of which is:
from shutil import copyfile
copyfile(src, dst)
# 2nd option
copy(src, dst) # dst can be a folder; use copy2() to preserve timestamp
- 将名为
src
的文件的内容复制到名为dst
的文件中.src
和dst
都需要是文件的完整文件名,包括路径. - 目标位置必须是可写的;否则,将引发
IOError
异常. - 如果
dst
已经存在,它将被替换. - 无法使用此功能复制字符或块设备和管道等特殊文件.
- 对于
copy
,src
和dst
是以str
s 给出的路径名. - Copy the contents of the file named
src
to a file nameddst
. Bothsrc
anddst
need to be the entire filename of the files, including path. - The destination location must be writable; otherwise, an
IOError
exception will be raised. - If
dst
already exists, it will be replaced. - Special files such as character or block devices and pipes cannot be copied with this function.
- With
copy
,src
anddst
are path names given asstr
s.
另一个要查看的 shutil
方法是 shutil.copy2()
.它很相似,但保留了更多元数据(例如时间戳).
Another shutil
method to look at is shutil.copy2()
. It's similar but preserves more metadata (e.g. time stamps).
如果您使用 os.path
操作,请使用 copy
而不是 copyfile
.copyfile
只接受字符串.
If you use os.path
operations, use copy
rather than copyfile
. copyfile
will only accept strings.
这篇关于如何在 Python 中复制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文