How To Read A File In Python

How To Read A File In Python

In this tutorial, we are going to see how to read a file in Python.

Python is a high-level programming language designed to be easy to read and simple to implement.

Reading a file means, reading its contents. There can be many methods of reading a file such as line by line, character by character, or complete file at a time.

How To Read A File In Python

We are using readlines() method to read file. This function reads all the lines in file. As it read file by line, there are newline characters at end of each line, it is always a good practice to get rid of them with strip("\n") if we want to process the contents further.


#f = open("C:/Python38/file.txt")  # specifying full path
  
f = open("file.txt")    # open file in current directory
lines = f.readlines()

for line in lines:
	print(line)

f.close()
  

Output

File Content : 

This is sample file content



to show working of python program to read a file

There are extra blank lines in output, because in code above we did not use remove the newlines at end of each line, and also print() attaches a newline while displaying string message on terminal. So thats why its looking that way.

Comments