Bpython_0
Bpython_0

Reputation: 3

Merging lines of a text file python

I have a text file with contents like this:

'artist
song
'artist2
song2
'artist3
song3
song4
'artist4
song5

And I want to print in the console:

song'artist
song2'artist2
song3'artist3
song4'artist3
song5'artist4

But the text file changes so I cant just merge specific lines. So far I have this code to merge the artist name, and the first song below the artists name, but when there is multiple songs by the same artist (as shown in the example text file above), I want it to print out all of the songs by that artist followed by the artists name, and not just the first song.

Here is my current code:

SongsFile = open('songs.txt', 'r')
Lines3 = SongsFile.readlines()
for line in Lines3:
    count += 1
    try:
        if line.startswith("\'"):
            x = count + 1
            at3.append(x)
            at4.append(line)
        if count = at3[0]:
            at3.clear()
            sa = line + at4[0]
            at4.clear()
            print(str(sa).replace("\n", " "))
    except:
        pass

This almost works, but instead of outputting what I want (example above), it outputs this (if the example file I gave above was used)

song'artist
song2'artist2
song3'artist3
song5'artist4

Sorry if this is confusing, I did my best to explain it.

Upvotes: 0

Views: 138

Answers (3)

Teejay Bruno
Teejay Bruno

Reputation: 2169

I think you may be overthinking it. See if the following code does what you want...

with open('songs.txt', 'r') as file:
    for line in file.readlines():
        if line.startswith("'"):
            artist = line
        else:
            print((line+artist).replace("\n",""))

Upvotes: 1

masonlai
masonlai

Reputation: 11

I have no idea what you wanna achieve. I think I could do better If I know your use case. I try to make something exactly same as your example

SongsFile = open('song.txt', 'r')
lines = SongsFile.readlines()
out = {}

currArtist = ''
for line in lines:
    line = line.replace('\n','')
    if line.startswith("\'"):
        currArtist = line
        out[currArtist] = []
    else:
        out[currArtist].append(line)


for index, (artist, songs) in enumerate(out.items()):
    for song in songs:
        print(song,artist)

result:

song 'artist
song2 'artist2
song3 'artist3
song4 'artist3
song5 'artist4

Upvotes: 0

ffsedd
ffsedd

Reputation: 305

I do not know what is wrong with your code, but this seems to work:

with open('songs.txt') as f:
    lines = f.readlines()
    
artist = ""
song = ""
out = []

for line in lines:
    if line.startswith("'"):
        artist = line.strip()
    else:
        song = line.strip()
        out.append(song + artist) 
    
text = "\n".join(out)     
print(text)   

Upvotes: 1

Related Questions