合并文本文件的行 python

Merging lines of a text file python

我有一个文本文件,内容如下:

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

我想在控制台打印:

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

但是文本文件发生了变化,所以我不能只合并特定的行。 到目前为止,我有这段代码可以合并艺术家姓名和艺术家姓名下方的第一首歌曲,但是当同一位艺术家有多首歌曲时(如上面的示例文本文件所示),我希望它打印出所有该艺术家的歌曲后跟艺术家的名字,而不仅仅是第一首歌。

这是我当前的代码:

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

这几乎可以工作,但它没有输出我想要的(上面的示例),而是输出这个(如果使用了我上面给出的示例文件)

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

抱歉,如果这让您感到困惑,我已尽力解释。

我不知道你的代码有什么问题,但这似乎有效:

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)   

我觉得你可能想多了。看看下面的代码是不是你想要的...

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

我不知道你想达到什么目的。如果我知道您的用例,我想我可以做得更好。我试着做一些和你的例子完全一样的东西

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)

结果:

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