Python复制和过去

时间:2017-05-29 15:47:21

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

我正在尝试使用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'

非常感谢任何帮助 感谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

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)))