python的初学者问题:如何在python中的文件中列出一个分隔行列表



作为一个初学者,我遇到了一个问题,这个问题让我尝试了很多次/方法,但仍然觉得很累,问题是我有一个用python读取的小文件,我必须列出整行,以按字母顺序排序。但当我试图把它列在一个列表中时,它会为每一行单独列出一个列表。

这是我的梅,我试图用它来解决问题:

file = open("romeo.txt")
for line in file:
words = line.split()
unique = list()
if words not in unique:
unique.extend(words)
unique.sort()
print(unique)

输出:

['But', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder']
['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the']
['Arise', 'and', 'envious', 'fair', 'kill', 'moon', 'sun', 'the']
['Who', 'already', 'and', 'grief', 'is', 'pale', 'sick', 'with']

要获得所有行的列表,可以使用简单的

with open(your_file, 'r') as f:
data = [''.join(x.split('n')) for x in f.readlines()] # I used simple list comprehension to delete the `n` at the end.

data中,每一行都在一个列表中。要对列表进行排序,必须使用sorted()

new_list = sorted(data)

现在CCD_ 3是排序列表。

您有一个内置的功能

lines_of_files = open("filename.txt").readlines()

这将返回文件中每一行的列表。希望这能解决你的问题

最新更新