Tutorials  Articles  Notifications  Login  Signup


DG

Dhirendra Gupta

Student at BIT Mesra Aug. 5, 2020, 10:17 a.m. ⋅ 893 views

Python read file


To read contents of any file using python we need to follow following steps:

  1. Open the file using open() function
  2. Read the contents of file using read() function
  3. Close the file using close() function

We need to pass full path of file location in open() function.

# Open file in read mode.
f = open("D:\\hacksersfriend\\welcome.txt", "r")

# Read contents of file using read function and print it
print(f.read())

# Close the file
f.close()

 

Read only some parts of the file

By default, read() function reads the entire content of the file. However, we can read only some portion of file by passing value of how many characters we want to read in read() function.

# Open file in read mode.
f = open("D:\\hacksersfriend\\welcome.txt", "r")

# This will read first 10 characters of file
print(f.read(10))

# Close the file
f.close()

 

Read line by line

We can read contents of file line by line using readline() function.

# Open file in read mode.
f = open("D:\\hacksersfriend\\welcome.txt", "r")

# This will read first line of file
print(f.readline())

# This will read second line of file
print(f.readline())

# Close the file
f.close()

 

We can also use a loop to read entire file line by line.

f = open("welcome.txt", "r")

for x in f:
  print(x)


f.close()

 

Reading files in binary mode

By default files are opened in text mode. This type is suitable for text files. However, if we want to read contents of any file type other that text, we need to open it in binary mode.

 

# Open file in binary mode
f = open("welcome.jpg", "rb")

# This will print binary representation of file
print(f.read())

#Close the file
f.close()

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account