Reputation: 1591
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..
Upvotes: 3
Views: 93
Reputation: 22443
I think that you would be better off running with:
file.rsplit(".",1)[0]
which would give you the path name to use for your directory.
The reason for using rsplit
rather than split
is just in case your files names have more than one full-stop in them
Note that you could achieve the same result with:
file.rpartition(".")[0]
Upvotes: 1
Reputation: 26578
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
.
Upvotes: 1