posted on 2023-05-03 20:25 read(430) 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
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.
name:
Comment content: (supports up to 255 characters)
Copyright © 2018-2021 python black hole network All Rights Reserved All rights reserved, and all rights reserved.京ICP备18063182号-7
For complaints and reports, and advertising cooperation, please contact vgs_info@163.com or QQ3083709327
Disclaimer: All articles on the website are uploaded by users and are only for readers' learning and communication use, and commercial use is prohibited. If the article involves pornography, reactionary, infringement and other illegal information, please report it to us and we will delete it immediately after verification!