2017-08-06 34 views
0

我有2个文件夹 - A和B.shutil.copy(),并在for循环中被赋予错误使用时shutil.move()

A包含---> empty.txt文件和empty.folder

B包含什么

1)shutil.copy代码()

path_of_files_folders=(r'C:\Users\Desktop\A') 

source=os.listdir(path_of_files_folders) 
print(source) 

destination=(r'C:\Users\Desktop\B') 

for files in source: 
    if files.endswith(".txt"): 
     print(files.__repr__()) 
     shutil.copy(files,destination) 

这给了我以下错误: -

Traceback (most recent call last): 
    File "C:/Users/Netskope/AppData/Local/Programs/Python/Python36-32 /shutil_1_copy.py", line 52, in <module> 
shutil.copy(files,destination) 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 235, in copy 
copyfile(src, dst, follow_symlinks=follow_symlinks) 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 114, in copyfile 
with open(src, 'rb') as fsrc: 
    FileNotFoundError: [Errno 2] No such file or directory: 'empty.txt' 

2)shutil.move()

path_of_files_folders=(r'C:\Users\Desktop\A') 
source=os.listdir(path_of_files_folders) 
print(source) 

destination=(r'C:\Users\Desktop\B') 

for files in source: 
    if files.endswith(".txt"): 
     print(files.__repr__()) 
     shutil.move(files,destination) 

码这给了我以下错误: -

Traceback (most recent call last): 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 538, in move 
    os.rename(src, real_dst) 
    FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empty.txt' -> 'C:\\Users\\Netskope\\AppData\\Local\\Programs\\Python\\Python36-32\\practice_1\\empty.txt' 

    During handling of the above exception, another exception occurred: 

    Traceback (most recent call last): 
    File "C:/Users/Netskope/AppData/Local/Programs/Python/Python36-32/shutil_1_copy.py", line 80, in <module> 
shutil.move(files,dest) 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 552, in move 
copy_function(src, real_dst) 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 251, in copy2 
copyfile(src, dst, follow_symlinks=follow_symlinks) 
    File "C:\Users\Netskope\AppData\Local\Programs\Python\Python36-32\lib\shutil.py", line 114, in copyfile 
with open(src, 'rb') as fsrc: 
    FileNotFoundError: [Errno 2] No such file or directory: 'empty.txt' 
+0

如果你只是想具体的文件,而不是全部你应该使用'glob.glob()'。例如 - glob.glob('*。txt')',详情请参阅这里 - https://docs.python.org/2/library/glob.html – droravr

回答

2

在您的代码文件只是文件名,不完整路径。 你必须改变你的代码是这样的:

shutil.copy(os.path.join(path_of_files_folders, files), destination) 
+0

谢谢你的工作 – Naif

1

你真的应该使用glob.glob()它会给你你在一个更简单的方法需要的东西:

import glob 

files = glob.glob('C:\Users\Desktop\A\*.txt') 

destination=(r'C:\Users\Desktop\B') 

for file_path in files: 
    print file_path 
    shutil.copy(file_path, destination) 
+0

谢谢。这也工作。 – Naif