【问题标题】:Python Copy and PastPython 复制和粘贴
【发布时间】:2017-05-29 15:47:20
【问题描述】:

我正在尝试使用 Python Shutil 模块将文件从一个文件夹复制粘贴到另一个文件夹,但它给了我一个错误,不确定是什么问题。

import os
import shutil

source = os.listdir("D:\Personal\TEST\SRC")
print source
destination = "D:\Personal\TEST\DEST"

for files in source:
    if files.endswith('.txt'):
        shutil.copy(files,destination)

Error:
File "C:/Users/xxx/xxx/config/scratches/test.py", line 10, 
in <module>
shutil.copy(files,destination)
File "C:\Python27\Lib\shutil.py", line 119, in copy
copyfile(src, dst)
File "C:\Python27\Lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'TEST.txt'

非常感谢任何帮助 谢谢。

【问题讨论】:

  • 好像listdir返回的是相对路径。
  • shutil.copy(files, destination)更改为for filename in files: shutil.copy(os.path.join(r"D:\Personal\TEST\src", filename), destination)

标签: python python-3.x shutil os.path


【解决方案1】:

试试这个:

import os
import shutil

source = r"D:\Personal\TEST\SRC"
destination = r"D:\Personal\TEST\DEST"

for file in [os.path.join(source, x) for x in os.listdir(source)]:
    if file.endswith('.txt'):
        shutil.copy(file, os.path.join(destination, os.path.basename(file)))

【讨论】:

  • @donjacob 那么请把答案标记为适当的答案,以便问题可以被视为关闭
猜你喜欢
  • 2015-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多