3 Advanced Methods to Read Files in Python

Here are three advanced methods to read files in Python. Python files methods open, read and close are part of io.py. The methods are file_object.read(), file_object.readline() and file_object.readlines().

File methods

The read(x) method will read only the number of characters that mentioned in the read method. Again, if you give multiple read methods then it will read in sequence.


What you'll learn here

  1. Example for read
  2. Example for readline
  3. Example for readlines


Method-1: read method

Here, file.txt is sample file with single row.


file.txt
abcdefghijk

file_object.read(2) ==> you will get 'ab'

file_object.read(4)  ===> you will get 'cdef'


Here, the multiple read methods read the data in sequence.


Method-2: readline method

Here, file.txt is sample file with single row.

file.txt

abcdefghijk

file_object.readline() ==> you will get 'abcdefghijk'

Here, it reads data line by line.


Method-3: readlines method

Here, file.txt is sample file with two rows rows.

file.txt

abcdefghijk
iiiooooooia

file_object.readlines() ==> you will get both the lines.


abcdefghijk
iiiooooooia


Here, it reads all the lines at a time.


Summary

  • I've demonstrated three methods
  • Useful for interviews and projects

Comments

Most Popular

7 AWS Interview Questions asked in Infosys, TCS

Hyperledger Fabric: 20 Real Interview Questions

How to Decode TLV Quickly