如何从Python3中的.txt文件从第1行打印到第N行?

时间:2018-04-05 15:11:19

标签: python python-3.x

我需要编写一个读取文本文件的python程序(songlist.txt - 其中包含以相反顺序存储在文本文件中的歌曲列表)以及将播放多少首歌曲。然后以正确的顺序打印歌曲列表 songlist.txt如下所示:

Hey Jude, The Beatles
Bohemian Rhapsody, Queen
American Pie, Don MacLean
Total Eclipse of the Heart, Bonnie Tyler
Creep, Radiohead
Bohemian Rhapsody, Queen
Piano Man, Billy Joel
Respect, Aretha Franklin
Thriller, Michael Jackson
Hotel California, Eagles

我可以使用此代码以正确的顺序打印完整的歌曲列表(文件songlist.txt的反向)

for line in reversed(list(open("songlist.txt"))):
    print(line.rstrip())

或使用以下代码打印最多N行的歌曲(错误的顺序 - 因为它没有反转):

N = int(input("How many more songs? "))

file = open('songlist.txt', 'r')

for i in range(1,N+1):
  A = file.readline()
  print(A)

但是我无法加入这两个代码以使其按预期工作;按正确的顺序打印N行(表示像下面一样打印歌曲列表):

我的程序应该像以下示例一样工作:

How many more songs? 2
Hotel California, Eagles
Thriller, Michael Jackson

下一个例子:

How many more songs? 4
Hotel California, Eagles
Thriller, Michael Jackson
Respect, Aretha Franklin
Piano Man, Billy Joel

问题可能太长了,但是,我被困在这里,感谢您的投入。

3 个答案:

答案 0 :(得分:1)

读入整个列表,反过来。

记住列表中的位置。

询问如何打印。

打印一个,前进位置,继续,直到达到所需数量或达到结束。

重复。

songs = """Hey Jude, The Beatles
Bohemian Rhapsody, Queen
American Pie, Don MacLean
Total Eclipse of the Heart, Bonnie Tyler
Creep, Radiohead
Bohemian Rhapsody, Queen
Piano Man, Billy Joel
Respect, Aretha Franklin
Thriller, Michael Jackson
Hotel California, Eagles"""


def getSongs():
    # """Read the file here and return it as list in the right order."""
    return songs.split("\n")[::-1] # return reversed list

allSongs = getSongs()
pos = 0   # position in the playlist
while True:
    N = int(input("How many more songs? "))
    for _ in range(N):
        print(allSongs[pos])     # print one
        pos += 1                 # advance
        if pos == len(allSongs): # more in list? continue else break from for
             break
    if pos == len(allSongs):     # more in list? continue else break from while
        break

输出:

How many more songs? 2
Hotel California, Eagles
Thriller, Michael Jackson
How many more songs? 3
Respect, Aretha Franklin
Piano Man, Billy Joel
Bohemian Rhapsody, Queen
How many more songs? 4
Creep, Radiohead
Total Eclipse of the Heart, Bonnie Tyler
American Pie, Don MacLean
Bohemian Rhapsody, Queen
How many more songs? 5
Hey Jude, The Beatles 

答案 1 :(得分:0)

所有归功于Patrick Artner的帮助,我能够解决这个问题。我知道这个代码可以提供,但对我有用 我的代码是:

songs = open('songlist.txt').read()

def getSongs():
    return songs.split("\n")[::-1] 

allSongs = getSongs()
pos = 1   
N = int(input("How many more songs? "))
for i in range(N):
        print(allSongs[pos])     
        pos += 1                 
        if pos == len(allSongs): 
             break

答案 2 :(得分:0)

line = int(input('还有多少首歌?'))

歌曲= open('songlist.txt')。read()

lista = songs.split(“ \ n”)[::-1]

i = 0 而我<行:

print(lista[i])

i += 1