Python - Chaînes en tant que fichiers

Lors de la lecture d'un fichier, il est lu comme un dictionnaire avec plusieurs éléments. Ainsi, nous pouvons accéder à chaque ligne du fichier en utilisant l'index de l'élément. Dans l'exemple ci-dessous, nous avons un fichier qui a plusieurs lignes et ces lignes deviennent des éléments individuels du fichier.

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]

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -

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.

Fichier sous forme de chaîne

Mais tout le contenu du fichier peut être lu comme une seule chaîne en supprimant le caractère de nouvelle ligne et en utilisant la fonction de lecture comme indiqué ci-dessous. Dans le résultat, il n'y a pas de lignes multiples.

with open("Path\GodFather.txt", 'r') as BigFile:
    data=BigFile.read().replace('\n', '')
	
# Verify the string type 
	print type(data)
	
# Print the file content
    print data

Lorsque nous exécutons le programme ci-dessus, nous obtenons la sortie suivante -


        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.