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

161 views Asked by At

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?

2

There are 2 answers

3
dzang On BEST ANSWER

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('/', '-')
0
Shubham Sharma On

You can use a slugify function which is defined below,

The slugify(value)

Code:

def slugify(value):
    """
    converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    value = re.sub(r'[^\w\s-]', '', value).strip().lower()
    value = re.sub(r'[-\s]+', '-', value)
    return value

Converts a string to a proper filename by:

  • Removing characters that aren’t alphanumerics, underscores, hyphens, or whitespace.
  • Removing leading and trailing whitespace.
  • Converting to lowercase.
  • Replacing any whitespace or repeated dashes with single dashes.

Usage:

>>> slugify('War Pigs / Luke's Wall - 2014 Remaster')

Output:

war-pigs-lukes-wall-2014-remaster