Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python match filenames and put in a folder

Tags:

python

Im trying to match all filenames in a folder, and put them into there own seperate folder with the name of the files. Heres an example:

2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.xml
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.doc
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.dox

2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.xml
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.doc
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.doc

I want to group these files into a folder, with the foldername being

2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1

Keep in mind there are hundreds of these files in a folder, I am trying to make them neater :)

What I got so far..

for file in os.listdir(src_path):
    if not os.path.isdir(dest_path + file.split("-")[:11]):
       os.mkdir(dest_path + file.split("-")[0])
shutil.copy(src_path + file, dest_path + file.split("-")[:11])

My thoughts were to match the first 11 digits..

like image 446
Anekdotin Avatar asked Feb 18 '26 09:02

Anekdotin


1 Answers

If you are looking to extract this:

2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1

You could grab the folder name you want much easier by simply splitting on the dot using splitext from os.path:

fname, fext = os.path.splitext('2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv')

fname will hold 2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1 fext will hold csv

Extra bit of information. Refrain from using file, it is a built-in for Python: https://docs.python.org/2/library/functions.html#file

It could lead to problems. Try fname or simply f.

like image 143
idjaw Avatar answered Feb 20 '26 23:02

idjaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!