Home  >  Article  >  Backend Development  >  python逐行读取文件内容的三种方法

python逐行读取文件内容的三种方法

WBOY
WBOYOriginal
2016-06-06 11:28:371304browse

方法一:

代码如下:


f = open("foo.txt")             # 返回一个文件对象 
line = f.readline()             # 调用文件的 readline()方法 
while line: 
    print line,                 # 后面跟 ',' 将忽略换行符 
    # print(line, end = '')   # 在 Python 3中使用 
    line = f.readline() 

f.close() 

方法二:

代码如下:


for line in open("foo.txt"): 
    print line, 

方法三:

代码如下:


f = open("c:\\1.txt","r") 
lines = f.readlines()#读取全部内容 
for line in lines 
    print line 

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn