Reputation: 871
I am trying to make a python script that will allow me to place music into one large folder so when I run the script it will create folders according to the first part of the music files. So let's say I have a music file called OMFG - Ice Cream.mp3
I would like to be able to split each music file name so that instead of OMFG - Ice Cream.mp3
it would chop it off in this case Ice Cream.mp3
and then it would use OMFG
to create a folder called that. After it created that folder I would then like to find out a way to then move, in this case OMFG - Ice Cream.mp3
into the folder that was just created.
Here is my code so far:
import os
# path = "/Users/alowe/Desktop/testdir2"
# os.listdir(path)
songlist = ['OMFG - Ice Cream.mp3', 'OMFG - Hello.mp3', 'Dillistone - Sad & High.mp3']
teststr = str(songlist)
songs = teststr.partition('-')[0]
print ''.join(songs)[2:-1]
My main trouble is how to loop through each object in the string.
Thanks, Alex
Upvotes: 1
Views: 3728
Reputation: 414149
It is convenient to use pathlib
module for such tasks:
#!/usr/bin/env python3
import sys
from pathlib import Path
src_dir = sys.argv[1] if len(sys.argv) > 1 else Path.home() / 'Music'
for path in Path(src_dir).glob('*.mp3'): # list all mp3 files in source directory
dst_dir, sep, name = path.name.partition('-')
if sep: # move the mp3 file if the hyphen is present in the name
dst_dir = path.parent / dst_dir.rstrip()
dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
path.replace(dst_dir / name.lstrip()) # move file
Example:
$ python3.5 move-mp3.py /Users/alowe/Desktop/testdir2
It moves OMFG - Ice Cream.mp3
to OMFG/Ice Cream.mp3
.
If you want to move OMFG - Ice Cream.mp3
to OMFG/OMFG - Ice Cream.mp3
:
#!/usr/bin/env python3.5
import sys
from pathlib import Path
src_dir = Path('/Users/alowe/Desktop/testdir2') # source directory
for path in src_dir.glob('*.mp3'): # list all mp3 files in source directory
if '-' in path.name: # move the mp3 file if the hyphen is present in the name
dst_dir = src_dir / path.name.split('-', 1)[0].rstrip() # destination
dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
path.replace(dst_dir / path.name) # move file
Upvotes: 2
Reputation: 1366
You can try out this code that:
Loops through the list
import os
import shutil
songlist = ['OMFG - Ice Cream.mp3', 'OMFG - Hello.mp3', 'Dillistone - Sad & High']
m_dir = '/path/mainfolder'
song_loc = '/path/songlocation'
for song in songlist:
s = song.split('-')
if os.path.exists(os.path.join(m_dir,s[0])):
shutil.copy(os.path.join(song_loc,song),os.path.join(m_dir,s[0].strip()))
else:
os.makedirs(os.path.join(m_dir,s[0]))
shutil.copy(os.path.join(song_loc,song),os.path.join(m_dir,s[0].strip()))
Upvotes: 1