user12759363
user12759363

Reputation:

Moving all .txt files in a directory to a new folder with os.walk()?

import os
import shutil
folder = 'c:\\Users\\myname\\documents'
for folderNames, subfolders, filenames in os.walk(folder):
    for file in filenames:
        if file.endswith('.txt'):
            shutil.copy(?????, 'c:\\Users\\myname\\documents\\putfileshere\\' + file)

This was simple to do for all .txt files in a folder by using os.listdir but I'm having trouble with this because in oswalk I don't know how to get the full filepath of the file that ends in .txt since it could be in however many subfolders

Not sure If I'm using the correct terminology of directory, but to be more clear I want to move all .txt files to the new folder even if it's 1,2,3 subfolders deep into the documents folder.

Upvotes: 1

Views: 818

Answers (2)

MrBean Bremen
MrBean Bremen

Reputation: 16805

To get the full path, you have to combine the root and filename parts. The root part points to the full path of the enumerated file names.

for root, _, filenames in os.walk(folder):
    for filename in filenames:
        if filename.endswith('.txt'):
            file_path = os.path.join(root, filename)
            shutil.copy(file_path, ...)

Upvotes: 1

Daniel Lima
Daniel Lima

Reputation: 995

You could also use glob.glob(pathname)

Upvotes: 0

Related Questions