Skip to content

Commit 0e4c568

Browse files
committed
Use a regex to delete characters. Change permissions. Move files to the root directory. Err when a title is not found. Ignore files.
1 parent 421b2d7 commit 0e4c568

1 file changed

Lines changed: 35 additions & 27 deletions

File tree

python2.7/music-organizer.py

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -5,46 +5,54 @@
55
import sys
66
from mutagen.easyid3 import EasyID3
77

8-
replaceChars = (
9-
(" ", "-"),
10-
("(", ""),
11-
(")", ""),
12-
(",", ""),
13-
(".", ""),
14-
("'", ""),
15-
("?", "")
16-
)
8+
emptyChars = re.compile(r"[(),.'\\\?]")
179
def toNeat(s):
1810
s = s.lower()
19-
for r in replaceChars: s = s.replace(r[0], r[1])
11+
s = s.replace(" ", "-")
12+
s = s.replace("&", "and")
13+
s = emptyChars.sub("", s)
2014
search = re.search("[^0-9a-z\-]", s)
2115
if search:
2216
print("Error: Unrecognized character in '" + s + "'")
2317
sys.exit(-42)
2418
return s
2519

2620
for dirname, dirnames, filenames in os.walk('.'):
27-
for subdirname in dirnames:
28-
print("subdir:" + str(subdirname))
21+
# Move all the files to the root directory.
2922
for filename in filenames:
30-
fullPath = os.path.join(dirname, filename)
31-
print("file: " + str(fullPath))
32-
audio = EasyID3(fullPath)
33-
title = audio['title'][0].decode()
34-
print(" title: " + title)
23+
ext = os.path.splitext(filename)[1]
24+
if ext == ".mp3":
25+
fullPath = os.path.join(dirname, filename)
26+
print("file: " + str(fullPath))
27+
audio = EasyID3(fullPath)
28+
title = audio['title'][0].decode()
29+
print(" title: " + title)
30+
31+
if not title:
32+
print("Error: title not found for '" + filename + "'")
33+
sys.exit(-42)
3534

36-
neatTitle = toNeat(title)
37-
print(" neat-title: " + neatTitle)
35+
neatTitle = toNeat(title)
36+
print(" neat-title: " + neatTitle)
3837

39-
ext = os.path.splitext(filename)[1]
40-
newFullPath = os.path.join(dirname, neatTitle + ext)
41-
print(" newFullPath: " + newFullPath)
38+
newFullPath = os.path.join(".", neatTitle + ext) # Remove subdirectories.
39+
print(" newFullPath: " + newFullPath)
4240

43-
if newFullPath != fullPath:
44-
if os.path.isfile(newFullPath):
45-
print("Error: File exists: '" + newFullPath + "'")
46-
sys.exit(-42)
41+
if newFullPath != fullPath:
42+
if os.path.isfile(newFullPath):
43+
print("Error: File exists: '" + newFullPath + "'")
44+
sys.exit(-42)
45+
46+
os.rename(fullPath, newFullPath)
47+
os.chmod(newFullPath, 0644)
48+
elif ext == ".pdf":
49+
pass
50+
else:
51+
print("Error: Unrecognized file extension in '" + filename + "'")
52+
sys.exit(-42)
4753

48-
os.rename(fullPath, newFullPath)
54+
# Delete all subdirectories.
55+
for subdirname in dirnames:
56+
os.rmdir(subdirname)
4957

5058
print("\nComplete!")

0 commit comments

Comments
 (0)