2014-11-25 63 views
6

我想按字母順序排列排序的文本文件字母(Python)的

shopping = open('shopping.txt') 
line=shopping.readline() 
while len(line)!=0: 
    print(line, end ='') 
    line=shopping.readline() 
#for eachline in myFile: 
# print(eachline) 
shopping.close() 

回答

6

使用sorted功能的文件「shopping.txt」排序。

with open('shopping.txt', 'r') as r: 
    for line in sorted(r): 
     print(line, end='') 
+1

請你讓我知道這是否會佔用內存中的所有行。這將如何工作。這是否懶惰地閱讀輸入。 – 2016-03-30 07:26:33

+1

@AkshayHazari:'sorted()'加載內存中的所有行。爲了避免加載所有行,可以調用外部'sort'命令或[在Python中實現它](http://stackoverflow.com/a/16954837/4279) – jfs 2017-02-23 08:42:30

14

一個簡單的方法,這是使用sort()sorted()功能做。

lines = shopping.readlines() 
lines.sort() 

或者:

lines = sorted(shopping.readlines()) 

的缺點是,你必須閱讀整個文件到內存中,雖然。如果這不是問題,您可以使用這個簡單的代碼。

18

只是爲了顯示不同的東西,而不是在Python這樣做,你可以在Unix系統在命令行裏這麼做:

sort shopping.txt -o shopping.txt 

和您的文件進行排序。當然,如果你真的想爲這個python:由許多其他人提出的解決方案提供閱讀文件和排序工作正常