简体   繁体   中英

Use Python to Create Folders Recursively with Folder Names Matching Filenames

Is there a Python method to create directories recursively? I have this path:

/home/data/ with files 'table1.csv', 'table2.csv', ... , 'table1000.csv' in it

I would like to create: /home/data/table1 and move 'table1.csv' in it; /home/data/table2 and move 'table2.csv' in it; . . . /home/data/table1000 and move 'table1000.csv' in it;

The folder names would have to match the csv file names.

How can I do it recursively? I know os.makedirs() should probably be used not sure how it works exactly.

Many thanks.

NOTE: 'table1' and 'table2' etc are just dummy example file names. The real filenames are a bit complex.

Use mkdir to create each dir, from the os library.

https://docs.python.org/2/library/os.html

For each dir move the current file using shutil.move .

How to move a file in Python

Each iteration should look like this:

for i in range(1, 1001):
    os.mkdir('/home/data/table' + str(i))
    shutil.move('/home/data/table' + str(i) + '.csv', '/home/data/table' + str(i) + '/table' + str(i) + '.csv')

I would work the following way in Python:

1.Get all files in folder in a list

2.Loop Through the filenames of the list and:

  1. Create Folder with the exact name (provided that you do not have duplicates)
  2. Move file in the folder
  3. Next File

A simple search in the net would get you ready examples on how to do each step of the above.

Edit: Below a simple example for csv files.

import glob, os
import shutil
dir="D:\Dropbox\MYDOCS\DEV\python\snippets"
os.chdir(dir)
for file in glob.glob("*.csv"):
    dst=dir+"\\"+file.replace(" ","_").replace(".csv","")
    os.mkdir(dst)
    print(dst)
    shutil.move(file,dst)

Used windows paths, since I use windows, you ll need to change that to linux paths.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM