在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:38:43  来源:igfitidea点击:

Copy file with pathlib in Python

pythonfilecopypython-2.xpathlib

提问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.Pathcreate a PosixPathobject if you're using Unix/Linux, WindowsPathif 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 Pathobject it will return the path that the Pathobject 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 Pathobjects (or subclasses thereof). That for older versions of Python this throws an error is because those implementations of shutilexpect string arguments for copy, and not pathlib.Pathtype 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 .copymethod on any of the Pathinstances. The argument to .copy()can be a file or a directory.

您可以将此代码放在您喜欢的任何位置,只要它在.copy对任何Path实例调用方法之前执行即可。参数.copy()可以是文件或目录。

回答by Geoff D

You can use pathlibrename method instead of shutil.move().

您可以使用pathlib重命名方法而不是shutil.move()。

import pathlib

my_file = pathlib.Path('/etc/hosts')
to_file = pathlib.Path('/tmp/foo')
my_file.rename(to_file)

回答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, pathlib2provides the read_bytes, read_text, write_bytesand write_textmethods.

对于Python 2.7,pathlib2提供read_bytesread_textwrite_byteswrite_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_bytesand read_bytesto copy text files, but if you need to deal with the encoding at copy time write_textan read_textpresent the advantage of two extra parameters:

按照该意见,可以使用write_bytesread_bytes复制文本文件,但如果你需要在副本的时间来处理与编码write_textread_text目前的两个额外的参数的优势:

  • encodingis the name of the encoding used to decode or encode the file
  • errorsis 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()