无法使用 python shutil 复制或移动文件

Unable to copy or move a file using python shutil

import shutil
import os

source = os.listdir("report")
destination = "archieved"

for files in source:
    if files.endswith(".json"):
        shutil.copy(files, destination)

我在报告文件夹 report/a.json 中有一个名为“a.json”的文件;但是,文件未moved/copied到目标文件夹

控制台错误:

*** FileNotFoundError: [Errno 2] No such file or directory: 'a.json'

os.listdir() returns 文件名而不是路径。在调用 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)