Python Project: Sorting Files by Type
Sorting files by type means grouping them by ending. The program reads a folder and moves each file to its group.
Take the ending
splitext()[1] gives the ending alone. The dot stays with it.
import os
print(os.path.splitext("photo.jpg")[1])Map endings to folders
The dict maps each ending to a folder name. ".jpg" maps to photos.
groups = {".txt": "text", ".jpg": "photos", ".mp3": "music"}
print(groups[".jpg"])Move one file
rename() moves a.txt into the text folder. The two checks prove the move.
import os
os.makedirs("sort_demo/text", exist_ok=True)
with open(os.path.join("sort_demo", "a.txt"), "w") as f:
f.write("a")
os.rename(os.path.join("sort_demo", "a.txt"), os.path.join("sort_demo", "text", "a.txt"))
print(os.path.exists(os.path.join("sort_demo", "a.txt")))
print(os.path.exists(os.path.join("sort_demo", "text", "a.txt")))Example
import os
groups = {".txt": "text", ".jpg": "photos", ".mp3": "music"}
os.makedirs("inbox", exist_ok=True)
for name in ["notes.txt", "list.txt", "cat.jpg", "dog.jpg", "song.mp3"]:
with open(os.path.join("inbox", name), "w") as f:
f.write("x")
for name in sorted(os.listdir("inbox")):
path = os.path.join("inbox", name)
if os.path.isdir(path):
continue
ext = os.path.splitext(name)[1]
folder = os.path.join("inbox", groups[ext])
os.makedirs(folder, exist_ok=True)
os.rename(path, os.path.join(folder, name))
for ext in sorted(groups, key=groups.get):
folder = groups[ext]
print(folder + ":", sorted(os.listdir(os.path.join("inbox", folder))))Key points
- Use os.listdir() to see the files in a folder
- Use os.path.splitext() to take the ending of each name
- Use os.rename() to move a file to a new path
- Use os.path.join() to build the new path
- Use a dict to map each ending to a folder name
- Use os.makedirs(folder, exist_ok=True) to make a group folder
In this example, the program builds an inbox first. It holds two text files, two photos, and one song. The loop reads the folder in sorted order. splitext() takes the ending of each name. The dict maps each ending to a group folder. rename() moves each file into its group. The last loop prints each group with its files.
Note
rename() moves the file. It leaves no copy behind.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What moves a file to a new path?