无法使用python shutil复制或移动文件
我在报告文件夹无法使用python shutil复制或移动文件,python,shutil,Python,Shutil,我在报告文件夹report/a.json中有一个名为“a.json”的文件;但是,文件不会移动/复制到目标文件夹 控制台错误: import shutil import os source = os.listdir("report") destination = "archieved" for files in source: if files.endswith(".json"): shutil.copy(files, destination) os.listdir
report/a.json
中有一个名为“a.json
”的文件;但是,文件不会移动/复制到目标文件夹
控制台错误:
import shutil
import os
source = os.listdir("report")
destination = "archieved"
for files in source:
if files.endswith(".json"):
shutil.copy(files, destination)
os.listdir()
返回文件名而不是路径。在调用shutil.copy()
之前,需要从文件名构造路径
如果“reports”是目录的路径,那么当给
shutil.copy
@Amdt时,文件名应该是“reports/a.json”。实际上,以前动态创建的json文件我不知道你的意思,但是如果在与“reports”相同的目录中有一个文件“a.json”,以及一个文件“reports/a.json”,您的操作将访问前者,而不是后者。通常,前一个不存在,这就是程序告诉你的。是的,这解决了我的问题;我同意你提到的说法;谢谢皮埃尔
*** FileNotFoundError: [Errno 2] No such file or directory: 'a.json'
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)