shutil.copy()和shutil.move()在for循环中使用时会出错

时间:2017-08-06 14:56:44

标签: python

我有2个文件夹 - A和B.

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'

2 个答案:

答案 0 :(得分:2)

在您的代码中文件只是文件名,没有完整路径。 您必须将代码更改为:

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

答案 1 :(得分:1)

你应该真的使用stackView它会以更简单的方式为你提供所需的东西:

glob.glob()