【发布时间】: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