1
import shutil
import os

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

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

I have the file named, 'a.json' inside the report folder report/a.json; however, the file is not moved/copied to the target folder

Console Error:

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

enter image description here

3
  • 2
    If "reports" is the path to the directory, the name of the file ought to be "reports/a.json" when given to shutil.copy. Commented Jun 9, 2018 at 19:27
  • @Amdt actually, the JSON file used to be created dynamically Commented Jun 9, 2018 at 19:38
  • I don't know what you mean, but if there is a file "a.json" in the same directory as "reports", and a file "reports/a.json", your operation will access the former one, not the latter. Usually, the former one doesn't exist, which is what the program is telling you. Commented Jun 9, 2018 at 19:40

1 Answer 1

2

os.listdir() returns filenames and not paths. You need to construct the paths from the filenames before calling 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)
Sign up to request clarification or add additional context in comments.

1 Comment

yes, this solved my issue; and I agree with the statement you've mentioned; thanks Pierre

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.