Bpython
Bpython

Reputation: 39

Appending text onto text file line by line Python

I have 2 arrays one of them being song names, and one being artist names, with number 1 in the artist names array being the artist for number 1 in the song names array, and so on. Currently I have put all the song names in a text file, by using a for loop, but i want to put the artist names next to the names of the corresponding songs in the same text file. Obviously, the code below isnt actual code, but if I want the real code to do something like that. Sorry if this is a confusing question

with open('songs.txt', 'r+') as f:
    for x in songnames:
        f.write(x + FOR I IN ARTISTS WRITE I)
    

Upvotes: 0

Views: 61

Answers (1)

Jiří Baum
Jiří Baum

Reputation: 6930

If the arrays have corresponding elements, you can use zip(), like this:

with open('songs.txt', 'r+') as f:
    for song, artist in zip(songnames, artists):
        f.write("%s: %s\n" % (song, artist))

Upvotes: 2

Related Questions