import shutil
import os
source = os.listdir("report")
destination = "archieved"
for files in source:
if files.endswith(".json"):
shutil.copy(files, destination)
我的文件名为' a.json
'在报告文件夹report/a.json
内;但是,文件不会移动/复制到目标文件夹
控制台错误:
*** FileNotFoundError: [Errno 2] No such file or directory: 'a.json'
答案 0 :(得分:2)
os.listdir()
返回文件名而不是路径。在调用shutil.copy()
之前,您需要从文件名构造路径。
import shutil
import os
source_directory_path = "report"
destination_directory_path = "archived"
for source_filename in os.listdir(source_directory_path):
if source_filename.endswith(".json"):
# construct path from filename
source_file_path = os.path.join(source_directory_path, source_filename)
shutil.copy(source_file_path, destination_directory_path)