News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Four Python methods to read file content line by line

posted on 2023-05-03 20:25     read(385)     comment(0)     like(22)     collect(0)


The following are four methods for Python to read the file content line by line, and analyze the advantages and disadvantages of each method and the application scenarios. The following codes have passed the test in python3, and some codes running in python2 have been commented and can be modified slightly.

Method 1: readline function
#- - coding: UTF-8 - -
f = open("/pythontab/code.txt") # return a file object
line = f.readline() # call the readline() method of the file
while line :
#print line, # In Python 2, followed by ',' will ignore the newline
print(line, end = '') # Use line in Python 3
= f.readline()
f.close()
Advantages: saving Memory, no need to put the content of the file into the memory at one time

Cons: relatively slow

Method 2: Read multiple rows of data at a time.
The code is as follows:

#- - coding: UTF-8 - -
f = open("/pythontab/code.txt")
while 1:
lines = f. readlines(10000)
if not lines:
break
for line in lines:
print(line)
f. close()
reads multiple lines at one time, which can improve the reading speed, but the memory usage is slightly larger, and the number of lines read at a time can be adjusted according to the situation

Method 3: Direct for loop
After Python 2.2, we can directly use a for loop to read each row of data on a file object

code show as below:

#-- coding: UTF-8 --
for line in open("/pythontab/code.txt"):
#print line, #python2 用法
print(line)

Method 4: Use fileinput module
import fileinput

for line in fileinput.input("/pythontab/code.txt"):
print(line)
is simple to use, but slower

Source: https://www.weidianyuedu.com



Category of website: technical article > Blog

Author:Sweethess

link:http://www.pythonblackhole.com/blog/article/268/cb1639579d49dc6baa73/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

22 0
collect article
collected

Comment content: (supports up to 255 characters)