将文件复制到目录 [英] Copy file to a directory

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

问题描述

我想用 shutil.copy() 函数将文件复制到另一个目录.我尝试执行以下代码:

I want to shutil.copy() function to copy file to another directory. I try to execute the following code:

copy(open("/home/dizpers/pytest/testfile1.txt", "r"), "/home/dizpers/pytest")

但是 python shell 显示了错误信息:

But python shell shows me the error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/shutil.py", line 116, in copy
    dst = os.path.join(dst, os.path.basename(src))
  File "/usr/lib/python2.7/posixpath.py", line 112, in basename
    i = p.rfind('/') + 1
AttributeError: 'file' object has no attribute 'rfind'

所以,我明白为什么会出现这个问题了.我用 open() 函数打开文件.而且我认为我也应该像这样打开一个目录.我该怎么做?

So, I understand why this problem appears. I open the file with open() function. And I think that I also should open a directory like this. How can I do this?

提前致谢!

推荐答案

shutil.copy 接受两个路径,不是文件对象和路径,你应该只指定路径而不是创建一个第一个参数的文件对象

shutil.copy takes in two paths, not a file object and a path, you should just specify the path instead of creating a file object for the first argument

如果需要,您可以使用 shutil.copyfileobj第一个参数使用文件对象,但第二个参数也必须使用文件对象.

You can use shutil.copyfileobj if you need to use a file object for the first argument, but you'll have to use a file object for the second argument as well.

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

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