Bobbert
Bobbert

Reputation: 29

Why won't python append to this file?

So, I'm working on this project where I have a 34mb text file full of song data. Each line has a year,artist,unique number and song separated by the string <SEP>. Now, I have sorted each of those things into different lists. What I want to do now is sort the artists into a different text file. The problem is python will create the file but will not print to it, the file size is 0 bytes. Here's my code:

#Opening the file to read here
with open('tracks_per_year.txt', 'r',encoding='utf8') as in_file:
    #Creating 'lists' to put information from array into
    years=[]
    uics=[]
    artists=[]
    songs=[]

    #Filling up the 'lists'
    for line in in_file:
        year,uic,artist,song=line.split("<SEP>")
        years.append(year)
        uics.append(uic)
        artists.append(artist)
        songs.append(song)
        print(year)
        print(uic)
        print(artist)
        print(song)



#Sorting:
with open('artistssorted.txt', 'a') as artist:

    for x in range(1000000):
        x=1
        if artists[x-1]==artists[x]:
            artist.write (years[x])
            artist.write(" ")
            artist.write(uics[x])
            artist.write(" ")
            artist.write(artists[x])
            artist.write(" ")
            artist.write(songs[x])
            artist.write("\n")
        else:
            x=x+1

Just FYI, uics= unique identifier codes Also, if you guys have any other recommendations on how to sort this file i'd be glad to hear it. Just keep in mind I am a novice.

Upvotes: 2

Views: 276

Answers (2)

Don
Don

Reputation: 17616

Here is my hit:

#Opening the file to read here
with open('tracks_per_year.txt', 'r',encoding='utf8') as in_file:
    #Creating 'lists' to put information from array into
    records = []

    #Filling up the 'lists'
    for line in in_file:
        year, uic, artist, song=line.split("<SEP>")
        records.append((artist, year, uic, song))

#Sorting:
records.sort()
with open('artistssorted.txt', 'a') as artist_file:

    for (artist, year,uic,song) in records:
        artist_file.write("%s %s %s %s\n"%(year, uic, artist, song))

Upvotes: 1

Eric Fortin
Eric Fortin

Reputation: 7603

Your condition if artists[x-1]==artists[x]: will always be false if the first 2 artists entry are not equals since you override x with 1 for every loop iteration. Writing in the file will then never happen.

When using range iteration, the variable gets incremented automatically so no need to do it yourself.

Upvotes: 2

Related Questions