在讀取文件時(shí),它被讀作具有多個(gè)元素的字典。 因此,我們可以使用元素的索引訪問(wèn)文件的每一行。在下面的示例中,有一個(gè)包含多行的文件,這些行成為文件的各個(gè)元素。
with open ("Path\GodFather.txt", "r") as BigFile:
data=BigFile.readlines()
# Print each line
for i in range(len(data)):
print "Line No- ",i
print data[i]
當(dāng)執(zhí)行上面示例代碼后,得到類似以下的結(jié)果 -
Line No- 0
Vito Corleone is the aging don (head) of the Corleone Mafia Family.
Line No- 1
His youngest son Michael has returned from WWII just in time to see the wedding of Connie Corleone (Michael's sister) to Carlo Rizzi.
Line No- 2
All of Michael's family is involved with the Mafia, but Michael just wants to live a normal life. Drug dealer Virgil Sollozzo is looking for Mafia families to offer him protection in exchange for a profit of the drug money.
Line No- 3
He approaches Don Corleone about it, but, much against the advice of the Don's lawyer Tom Hagen, the Don is morally against the use of drugs, and turns down the offer.
Line No- 4
This does not please Sollozzo, who has the Don shot down by some of his hit men.
Line No- 5
The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.
文件作為字符串
但是,通過(guò)刪除新行字符并使用read
函數(shù),可以將整個(gè)文件內(nèi)容讀取為單個(gè)字符串,如下所示。結(jié)果中沒有分行。
當(dāng)執(zhí)行上面示例代碼后,得到類似以下的結(jié)果 -
Vito Corleone is the aging don (head) of the Corleone Mafia Family. His youngest son Michael has returned from WWII just in time to see the wedding of Connie Corleone (Michael's sister) to Carlo Rizzi. All of Michael's family is involved with the Mafia, but Michael just wants to live a normal life. Drug dealer Virgil Sollozzo is looking for Mafia families to offer him protection in exchange for a profit of the drug money. He approaches Don Corleone about it, but, much against the advice of the Don's lawyer Tom Hagen, the Don is morally against the use of drugs, and turns down the offer.This does not please Sollozzo, who has the Don shot down by some of his hit men. The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.