Python – 将字符串作为文件

Python – 将字符串作为文件

读取文件后,它被视为一个具有多个元素的字典。因此,我们可以使用元素的索引访问文件的每一行。 在下面的示例中,我们有一个包含多行的文件,这些行将成为文件的单独元素。

with open ("Path\GodFather.txt", "r") as BigFile:
    data=BigFile.readlines()

#打印每一行
    for i in range(len(data)):
    print "第",i,"行" 
    print data[i]

当我们运行上述程序时,我们会得到以下输出 −

第 0 行
Vito Corleone is the aging don (head) of the Corleone Mafia Family. 

第 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. 

第 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. 

第 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.

第 4 行
This does not please Sollozzo, who has the Don shot down by some of his hit men. 

第 5 行
The Don barely survives, which leads his son Michael to begin a violent mob war against Sollozzo and tears the Corleone family apart.

将文件作为字符串

但是,通过删除换行符并使用 read 函数,可以将整个文件内容作为单个字符串读取,如下所示。结果中没有多个行。

with open("Path\GodFather.txt", 'r') as BigFile:
    data=BigFile.read().replace('\n', '')

#验证字符串类型 
    print type(data)

#打印文件内容
    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.

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程