Search code examples
pythoncsvfilequote

Avoid writing quotes to text file with comma present in string in Python


My code currently searches for files that end with any audio file extension, returns the file name and then stores the path + file name into a text file.

Simple enough, it works, but when scrolling through I noticed some entries have quotes around the entire line. These would be the ones that the file name has a comma in;

Screenshot

This is the code:

def getFiles():
    tracks = []
    for root, dirs, files in os.walk("E:\Music"):
        for name in files:
            if name.endswith((".mp3",".m4a",".alac",".flac")):
                tracks.append(root+"\\"+name)
    return tracks

with open("songs.txt", "a") as songsFile:
writeSongsFile = csv.writer(songsFile)
for line in getFiles():
    writeSongsFile.writerow([line])
songsFile.close()

How do I write the file path to the text file without the quotes?


Solution

  • The reason you're getting quotes around any value that has a comma in it is because you're using csv.writer to print out your song list.

    See, csv is a module meant to work with Comma-Separated Value files (i.e. spreadsheets where each column is separated by a comma: col1, col2, col3, ...). As a result, if one of those columns contains a comma, it needs to be escaped, and the most convenient way to do that is by putting the whole thing in quotes. The csv module knows this, and does it automatically.

    Here, however, it looks like you just want to put this list in a file. No commas or anything, just a list separated by line breaks. In this case, you don't need to use the csv module - in fact, I recommend against it, for exactly the issue you're having. Use python's built-in file I/O instead:

    with open("songs.txt", "a") as songsFile:
        for line in getFiles():
            songsFile.write(line + '\n')