我想按字母順序排列排序的文本文件字母(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()
我想按字母順序排列排序的文本文件字母(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()
使用sorted
功能的文件「shopping.txt」排序。
with open('shopping.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
一個簡單的方法,這是使用sort()
或sorted()
功能做。
lines = shopping.readlines()
lines.sort()
或者:
lines = sorted(shopping.readlines())
的缺點是,你必須閱讀整個文件到內存中,雖然。如果這不是問題,您可以使用這個簡單的代碼。
只是爲了顯示不同的東西,而不是在Python這樣做,你可以在Unix系統在命令行裏這麼做:
sort shopping.txt -o shopping.txt
和您的文件進行排序。當然,如果你真的想爲這個python:由許多其他人提出的解決方案提供閱讀文件和排序工作正常
請你讓我知道這是否會佔用內存中的所有行。這將如何工作。這是否懶惰地閱讀輸入。 – 2016-03-30 07:26:33
@AkshayHazari:'sorted()'加載內存中的所有行。爲了避免加載所有行,可以調用外部'sort'命令或[在Python中實現它](http://stackoverflow.com/a/16954837/4279) – jfs 2017-02-23 08:42:30