Is there a way to determine if an mp3 file was downloaded on PC and to replace it to another folder?
For example - I downloaded a new song. It was downloaded to the Downloads folder, but I want to automatically replace the song to the Music folder.
Is it possible with Python?
Asked
Active
Viewed 59 times
-2
Alex Zab
- 312
- 2
- 18
3 Answers
2
You can do this by using the builtin "os" library in python.
import os
from os import path
file_to_check = "somefile.mp3"
from_path = "~/Downloads/" + file_to_check
to_path = "~/Music/" + file_to_check
if path.exists(from_path):
os.rename(from_path, to_path)
(EDIT based on comment) In the case you don't know the name of the file this would work by moving all .mp3 files to the Music folder:
for song_file in os.listdir("Downloads/"):
if song_file.endswith(".mp3"):
os.rename("Music/" + song_file)
Aasim Sani
- 335
- 2
- 6
-
What if I don't know the name of the `mp3` file? – Alex Zab Dec 20 '20 at 15:40
-
1Can you provide a bit more detail are you searching for all mp3 files and moving them? – Aasim Sani Dec 20 '20 at 15:42
-
My idea is when `mp3` file downloaded it must be replaced. Doesn't matter what name of this file and how many files – Alex Zab Dec 20 '20 at 15:46
-
Added how to do that to the answer. – Aasim Sani Dec 20 '20 at 15:48
-
I'll put it in `while True` so they will move anytime – Alex Zab Dec 20 '20 at 15:49
-
While that can work it is not the best practice. You can you use the `datetime` library to make it run at a fixed interval. [Example here](https://stackoverflow.com/questions/15088037/python-script-to-do-something-at-the-same-time-every-day) – Aasim Sani Dec 20 '20 at 15:54
0
The pathlib will have all the functionality you need.
Here is an example:
from pathlib import Path
source = Path('path_to_source_mp3')
dest = Path('path_to_dest_mp3')
if source.exists():
source.replace(dest)
Lior Cohen
- 5,227
- 1
- 13
- 28
0
The final code is -
import os
from os import path
from_path = 'C:/Users/username/Downloads/'
for file in os.listdir(from_path):
if file.endswith('.mp3'):
from_path = 'C:/Users/username/Downloads/' + file
to_path = 'C:/Users/username/Music/' + file
os.rename(from_path, to_path)
print("Moved")