user5778614 user5778614 - 4 months ago 6x
Python Question

Python script to extract all subdirectories according to filename

My directory contains several folders, each with several subdirectories of their own. I need to move all of the files that contain 'Volume.csv' into a directory called Volume.




I'm trying combinations of os.walk and regex to retrieve the files by filename but not having much luck.

Any ideas?

Thank you!

Sunworshipper, thank you for the answer!

I ran the following code and it moved the entire directory rather than just file name containing 'Volume'. Is it clear why that happened?

import os
import shutil

source_dir = "~/Stats/"
dest_dir = "~/Stats/Volume/"

file_paths = set()

for dir_, _, files in os.walk(source_dir):
for fileName in files:
if "Volume" in fileName:
relDir = os.path.relpath(dir_, source_dir)

for matched in file_paths:
shutil.move(matched, dest_dir)


You can use glob for this. It returns a list of path names matching the expression you give it.

import glob
import shutil

dest = 'testfiles/'

files = glob.glob('*/*test.csv')

for file in files:
    shutil.move(file, dest)

I used relative paths but you can also use absolute paths. shutil moves the documents to the new location. See the glob.glob documentation for more info.