SoFunction
Updated on 2024-11-12

Summary of Python's methods for reading the contents of a file line by line

Python's four ways to read the contents of a file line by line

The following four Python methods to read the contents of the file line by line, analyze the advantages and disadvantages of various methods and application scenarios, the following code in python3 test passed, python2 run some of the code has been commented, a little modification can be.

Method 1: readline function

# -*- coding: UTF-8 -*-
f = open("/pythontab/") # Returns a file object
line = () # Call the file's readline() method
while line:
  # print line, # In Python 2, ',' followed by ',' ignores the newline character
  print(line, end='') # Use in Python 3
  line = ()
()

Pros: memory saving, no need to put the file contents into memory all at once.
Cons: Relatively slow.

Method 2: Read multiple rows of data at once

The code is as follows:
# -*- coding: UTF-8 -*-
f = open("/pythontab/")
while 1:
  lines = (10000)
  if not lines:
    break
  for line in lines:
    print(line)
()

Read multiple lines at once, you can improve the reading speed, but the memory use is a little large, you can adjust the number of lines read at a time according to the situation

Method 3: Direct for loop

You can read each line of data directly into a file object using a for loop as follows.

# -*- coding: UTF-8 -*-
for line in open("/pythontab/"):
  # print line, #python2 usage
  print(line)

Method 4: Use the fileinput module

import fileinput
for line in ("/pythontab/"):
  print(line)

Easy to use, but slow

These are all the relevant points in this presentation, thank you for learning and supporting me.