Python-파일로서의 문자열

파일을 읽는 동안 여러 요소가있는 사전으로 읽습니다. 따라서 요소의 인덱스를 사용하여 파일의 각 줄에 액세스 할 수 있습니다. 아래 예제에서 우리는 여러 줄이있는 파일을 가지고 있으며 그 줄은 파일의 개별 요소가됩니다.

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]

위의 프로그램을 실행하면 다음과 같은 결과가 나옵니다.

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.

문자열로 파일

그러나 전체 파일 내용은 줄 바꿈 문자를 제거하고 아래와 같이 읽기 기능을 사용하여 단일 문자열로 읽을 수 있습니다. 결과적으로 여러 줄이 없습니다.

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

위의 프로그램을 실행하면 다음과 같은 결과가 나옵니다.


        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.