user5778614 user5778614 - 5 months ago 17
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.

Folder1
|---1Area.csv
|---1Circumf.csv
|---1Volume.csv

Folder2
|---2Area.csv
|---2Circumf.csv
|---2Volume.csv

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)
file_paths.add(relDir)

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

Answer

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.

Comments