Search code examples
pythonstringfileresponse.write

Python file writing error because of "/" in the file name


I have a code chunk like this

for track in (results['tracks']):
        track_id_chunk.append(track['uri'])
        print (str(z) + " - " + track['name'])
        try:
            r = requests.get(track['preview_url'], allow_redirects=True)
            open('dataset/'+genres[x]+"/"+str(track['name'])+'.mp3', 'wb').write(r.content)
        except requests.exceptions.RequestException as e:
            print ("---------------------- Couldnt get "+artists[j]+"  -  "+track['name'] + " !!!")
            continue
        z+=1

It downloads 30 seconds samples of artists given externally using spotify API.

The problem is when a song has a "/" in its name ("War Pigs / Luke's Wall - 2014 Remaster" for example) the file operation looks for the directory before "/", fails to find it and throws error:

FileNotFoundError: [Errno 2] No such file or directory: "dataset/metal/War Pigs / Luke's Wall - 2014 Remaster.mp3"

what is the best practice workaround or solution for this problem?


Solution

  • If you are on Linux you can't have slashes in your filename. My suggestion is to replace the character with something else like '-':

    str(track['name']).replace('/', '-')