简体   繁体   English

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

[英]How to print from line 1 to line N from a .txt file in Python3?

I need to write a python program that reads in a text file (songlist.txt - which has list of songs stored in a text file reverse order) and how many more songs will be sung.我需要编写一个 python 程序来读取一个文本文件(songlist.txt - 它有以文本文件相反顺序存储的歌曲列表)以及将要唱多少首歌曲。 Then it prints song list in the correct order.然后它以正确的顺序打印歌曲列表。
songlist.txt reads like following: 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

I am able to either print complete songlist in correct order(reverse of file songlist.txt) with this code我可以使用此代码以正确的顺序(与文件 songlist.txt 相反)打印完整的歌曲列表

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

or print songs upto N lines (incorrect order - because it's not reversed) with the following code:或使用以下代码将歌曲打印到 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)

However I am unable to join these two codes to make it work as intended;但是我无法加入这两个代码以使其按预期工作; print upto N lines in correct order (means print song list like follwong):以正确的顺序打印最多 N 行(意味着像 follwong 一样打印歌曲列表):

My program should work like the following examples:我的程序应该像下面的例子一样工作:

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

Next example:下一个例子:

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

Question might be too long, however, I'm stuck here, thanks for your inputs.问题可能太长了,但是,我被困在这里,感谢您的投入。

Read in the whole list, reverse it.阅读整个列表,反转它。

Remember where in the list you are.记住您在列表中的位置。

Ask for how may to print.询问如何打印。

Print one, advance position, continue until you reached the amount needed or the end is reached.打印一张,前进位置,继续直到达到所需数量或到达终点。

Repeat.重复。

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

Output:输出:

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 

All credit goes to Patrick Artner for his help, I am able to solve this one.所有功劳都归功于帕特里克·阿特纳 (Patrick Artner) 的帮助,我能够解决这个问题。 I know this code can be furnished, however worked for me.我知道可以提供此代码,但对我有用。
My code is:我的代码是:

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

line = int(input('How many more songs? ')) line = int(input('还有几首歌曲?'))

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

lista = songs.split("\\n")[::-1] lista = Songs.split("\\n")[::-1]

i = 0 while i < line: i = 0 而 i < 行:

print(lista[i])

i += 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM