Python – string as file
Python – Reading Strings as Files
After reading a file, it is treated as a dictionary with multiple elements. Therefore, we can access each line of the file using the element’s index. In the following example, we have a file with multiple lines, and these lines will become individual elements of the file.
with open ("PathGodFather.txt", "r") as BigFile:
data=BigFile.readlines()
#Print each line
for i in range(len(data)):
print "第",i,"线"
print data[i]
When we run the above program, we get the following output −
Line 0
Vito Corleone is the aging don (head) of the Corleone Mafia Family.
Line 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 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 profit from the drug money.
Line 3
He approaches Don Corleone about it, but, much against the advice of the Don's lawyer, Tom Hagen, the Don is morally opposed to the use of drugs, and turns down the offer.
Line 4
This does not please Sollozzo, who has the Don shot down by some of his hit men.
Line 5
The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.
File as a String
However, by removing the newline character and using the read function, the entire file contents can be read as a single string, as shown below. The result does not have multiple lines.
with open("PathGodFather.txt", 'r') as BigFile:
data=BigFile.read().replace('n', '')
#Verify string type
print type(data)
#Print file contents
print data
When we run the above program, we get the following output −
<br>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 from 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.