python read file content line by line

1. After using open to open a file, you must remember to call the close() method of the file object. For example, try/finally statements can be used to ensure that the file is finally closed.

2. Need to import import os

Third, the following are three ways to read the contents of a file line by line:

1. The first method:

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

2. The second method:

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

3. The third method:

f = open("c:\\1.txt","r")   
lines = f.readlines()      #读取全部内容 ,并以列表方式返回  
for line in lines   
    print line

Fourth, read the entire file content at one time:

file_object = open('thefile.txt')  
try:  
     all_the_text = file_object.read()  
finally:  
     file_object.close()  

5. Treat reading text and binary differently: 1. If it is reading text

读文本文件  
input = open('data', 'r')  
#第二个参数默认为r  
input = open('data')  

2. If it is to read binary

input = open('data', 'rb') 

3. Read fixed bytes

chunk = input.read(100)  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325251209&siteId=291194637