在Python中使用pathlib复制文件 [英] Copy file with pathlib in Python

查看:107
本文介绍了在Python中使用pathlib复制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 pathlib

import pathlib
import shutil

my_file=pathlib.Path('/etc/hosts')
to_file=pathlib.Path('/tmp/foo')
shutil.copy(my_file, to_file)

我收到此异常:

/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

...如何在Python 2.7中使用pathlib复制文件?

... how to copy file with pathlib in Python 2.7?

推荐答案

要使用问题是 pathlib.Path 如果使用Unix/Linux,则创建 PosixPath 对象;如果使用Microsoft,则创建 WindowsPath Windows.

The problem is pathlib.Path create a PosixPath object if you're using Unix/Linux, WindowsPath if you're using Microsoft Windows.

在旧版本的Python中, shutil.copy 需要一个字符串作为其参数.对于他们,请在此处使用 str 函数.

With older versions of Python, shutil.copy requires a string as its arguments. For them, use the str function here.

这篇关于在Python中使用pathlib复制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆