-2

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?

Alex Zab
  • 312
  • 2
  • 18

3 Answers3

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
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")