在 Python 中使用 pathlib 复制文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33625931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy file with pathlib in Python
提问by guettli
I try to copy a file with pathlib
我尝试复制一个文件 pathlib
import pathlib
import shutil
my_file=pathlib.Path('/etc/hosts')
to_file=pathlib.Path('/tmp/foo')
shutil.copy(my_file, to_file)
I get this exception:
我得到这个例外:
/home/foo_egs_d/bin/python /home/foo_egs_d/src/test-pathlib-copy.py
Traceback (most recent call last):
File "/home/foo_egs_d/src/test-pathlib-copy.py", line 6, in <module>
shutil.copy(my_file, to_file)
File "/usr/lib/python2.7/shutil.py", line 117, in copy
if os.path.isdir(dst):
File "/home/foo_egs_d/lib/python2.7/genericpath.py", line 41, in isdir
st = os.stat(s)
TypeError: coercing to Unicode: need string or buffer, PosixPath found
Process finished with exit code
... how to copy file with pathlib in Python 2.7?
...如何在 Python 2.7 中使用 pathlib 复制文件?
采纳答案by Kevin Guan
So what about this?
那么这个呢?
import pathlib
import shutil
my_file = pathlib.Path('/etc/hosts')
to_file = pathlib.Path('/tmp/foo')
shutil.copy(str(my_file), str(to_file))
The problem is pathlib.Path
create a PosixPath
object if you're using Unix/Linux, WindowsPath
if you're using Microsoft Windows.
问题是如果您使用的是 Unix/Linux,如果您使用的是 Microsoft Windows ,则pathlib.Path
创建一个PosixPath
对象WindowsPath
。
But shutil.copy()
takes a string as its argument. So just use the str()
function here, when you use str()
function on a Path
object it will return the path that the Path
object refers to as a string.
但是shutil.copy()
需要一个字符串作为它的参数。所以在str()
这里只使用函数,当你str()
在Path
对象上使用函数时,它会返回Path
对象作为字符串引用的路径。
回答by Anthon
The cause for shutil.copy()
not working is that you are not using the latest Python, Python 3.6 shutil.copy()
canhandle Path
objects (or subclasses thereof). That for older versions of Python this throws an error is because those implementations of shutil
expect string arguments for copy
, and not pathlib.Path
type arguments.
shutil.copy()
不工作的原因是你没有使用最新的 Python,Python 3.6shutil.copy()
可以处理Path
对象(或其子类)。对于旧版本的 Python,这会引发错误,因为这些实现的shutil
期望字符串参数为copy
,而不是pathlib.Path
类型参数。
What you actually want to be able to write is:
你真正想要能够写的是:
my_file.copy(to_file)
You can subclass Path to include such a method, and adapt the creation of my_file
. I find it easier to just graft/monkey-patch/duck-punch it on the existing pathlib.Path
您可以将 Path 子类化以包含这样的方法,并适应my_file
. 我发现在现有的设备上移植/猴子补丁/鸭子打孔更容易pathlib.Path
from pathlib import Path
def _copy(self, target):
import shutil
assert self.is_file()
shutil.copy(str(self), str(target)) # str() only there for Python < (3, 6)
Path.copy = _copy
You can put this code anywhere you like, as long as it gets executed before calling the .copy
method on any of the Path
instances. The argument to .copy()
can be a file or a directory.
您可以将此代码放在您喜欢的任何位置,只要它在.copy
对任何Path
实例调用方法之前执行即可。参数.copy()
可以是文件或目录。
回答by Geoff D
回答by Jacques Gaudin
Since Python 3.5, without importing shutil
, you can do:
从 Python 3.5 开始,无需导入shutil
,您可以执行以下操作:
from pathlib import Path
dest = Path('dest')
src = Path('src')
dest.write_bytes(src.read_bytes()) #for binary files
dest.write_text(src.read_text()) #for text files
For Python 2.7, pathlib2
provides the read_bytes
, read_text
, write_bytes
and write_text
methods.
对于Python 2.7,pathlib2
提供read_bytes
,read_text
,write_bytes
和write_text
方法。
The file will be loaded in memory, so this method is not suitable for files larger than the machines available memory.
文件会加载到内存中,所以这种方法不适合大于机器可用内存的文件。
As per the comments, one can use write_bytes
and read_bytes
to copy text files, but if you need to deal with the encoding at copy time write_text
an read_text
present the advantage of two extra parameters:
按照该意见,可以使用write_bytes
和read_bytes
复制文本文件,但如果你需要在副本的时间来处理与编码write_text
的read_text
目前的两个额外的参数的优势:
encoding
is the name of the encoding used to decode or encode the fileerrors
is an optional string that specifies how encoding and decoding errors are to be handled
encoding
是用于解码或编码文件的编码名称errors
是一个可选字符串,指定如何处理编码和解码错误
They both have the same meaning as in open()
.
它们都具有与 中相同的含义open()
。