Elodin86
Elodin86

Reputation: 35

How to use the file path as the source parameter from os.walk to copy files

Okay, so I'm not sure how to get python to use the path to a file that it found through an os.walk function as the source parameter for the shutil.copy(source, destination) arguments.

My code example is this

for folderName, subfolders, filenames in os.walk('/Users/me/Documents'):
    print('The current folder is '+folderName)
    for subfolder in subfolders:
        print('SUBFOLDER OF '+folderName+": "+subfolder)
    for filename in filenames:
        print("FILE INSIDE "+folderName+": "+filename)
        if filename.endswith('.txt'):
            os.chdir(filename)
            shutil.copy(filename, '/Users/me/Documents/School/IT 145/Text Files')
    print("")

If the file has a .txt extension, I would like python to copy that file to the specified folder.

My error message I get is this

The current folder is /Users/me/Documents/Text Files
FILE INSIDE /Users/me/Documents/Text Files: guest.txt
Traceback (most recent call last):
  File "/Users/me/Documents/School/IT 145/Programming Work/os_walk.py", line 16, in <module>
    os.chdir(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'guest.txt'

From what I understand, python is going back to the current working directory to do the shutil.copy, but I don't understand why if I pass it the file path that it just found it won't use that as the source path for the file to copy.

This is my first ever python programming class, and really my first brush with python all, so any teaching thoughts would be greatly appreciated. Thank you very much.

Upvotes: 1

Views: 209

Answers (1)

costaparas
costaparas

Reputation: 5237

Your current code never leaves its original working directory. You can verify this by running:

print(os.getcwd())

Your os.walk() does not change the current directory (CWD).

Your attempt at changing the CWD:

os.chdir(filename)

does not work since filename is a file name and not a directory.

os.chdir(folderName)

would work.

You could use the approach of changing into the directory just to copy the file. But, you can't be doing that it every iteration of your loop, either -- only on the first. Or, better yet, you could change into the directory at the start. In any case, I advice against this approach since its an unnecessary overhead.

Instead, just prefix the filename with its parent directory -- i.e. folderName when you call shutil.copy().

For example:

shutil.copy(os.path.join(folderName, filename), '/Users/me/Documents/School/IT 145/Text Files')

Side note for readability: Put '/Users/me/Documents' and '/Users/me/Documents/School/IT 145/Text Files' into named variables -- which makes it easier to read, change and/or reuse if needed.

Side note for portability: Aim to use os.path.join() instead of using / for the directory separator.

Upvotes: 1

Related Questions