2017-08-06 31 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