【问题标题】:How to print from line 1 to line N from a .txt file in Python3?如何从 Python3 中的 .txt 文件从第 1 行打印到第 N 行?
【发布时间】:2018-04-05 15:11:19
【问题描述】:

我需要编写一个 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 行(意味着打印歌曲列表,如 follwong):

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

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

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

【问题讨论】:

  • 可以直接反转输入的歌单吗?这里有一个例子:stackoverflow.com/questions/742466/…
  • 这在 Python3 中没有解决,不过感谢您的建议。
  • 所以你不能在 Python 之外使用 unix shell 之类的工具更改文件?

标签: python python-3.x


【解决方案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 

【讨论】:

  • 谢谢帕特里克,你是最棒的。在您的帮助和少量修改下,这解决了。感谢您抽出宝贵时间阅读并解决这个冗长的问题。
【解决方案2】:

感谢 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

【讨论】:

    【解决方案3】:

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

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

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

    我 = 0 而我

    print(lista[i])
    
    i += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-30
      相关资源
      最近更新 更多