很多時(shí)候,我們需要對(duì)文件的內(nèi)容進(jìn)行排序以進(jìn)行分析。 例如,我們希望得到不同學(xué)生寫的句子,按名稱的字母順序排列。 這將涉及排序不僅僅是行的第一個(gè)字符,而是從左邊開(kāi)始的所有字符。 在下面的程序中,首先從文件中讀取行,然后使用sort函數(shù)打印它們,sort函數(shù)是標(biāo)準(zhǔn)python庫(kù)的一部分。
打印文件
FileName = ("D:/path/poem.txt")
data=file(FileName).readlines()
for i in range(len(data)):
print data[i]
當(dāng)我們運(yùn)行上面的程序時(shí),得到以下輸出 -
Summer is here.
Sky is bright.
Birds are gone.
Nests are empty.
Where is Rain?
現(xiàn)在在打印文件內(nèi)容之前應(yīng)用sort函數(shù)。這些行根據(jù)左邊的第一個(gè)字母排序。
FileName = ("D:\pathto\poem.txt")
data=file(FileName).readlines()
data.sort()
for i in range(len(data)):
print data[i]
當(dāng)我們運(yùn)行上面的程序時(shí),得到以下輸出 -
Birds are gone.
Nests are empty.
Sky is bright.
Summer is here.
Where is Rain?