Python – Read a file example

Python – Read a file example

Python provides inbuilt function to read a file. We don’t need to import any external library. In this tutorial, we will demonstrate examples to read content of file and read content line by line in case data is big or you want to do some other operations like line parsing. We will read plain text file named code2succeed.txt, here are the content of file.

Code2Succeed - Help You Grow
www.code2succeed.com\n
Help You Grow is main motto. Organized and well formatted approach of concepts and various examples.

Line 1\t\n
Line 2\n  
Line 3

1) Read content of the file.

def readContent():
    file = open('code2succeed.txt', 'r')
    content = file.read()
    print(content)
    
if __name__ == '__main__':
    readContent()

In above example, we follow below steps to read a file.
Step 1: Open the file in read mode.

file = open('code2succeed.txt', 'r')

Step 2: Read content of file using file.read() and assign to variable content.
Step 3: print content of file to console.

Output
Code2Succeed - Help You Grow
www.code2succeed.com\n
Help You Grow is main motto. Organized and well formatted approach of concepts and various examples.

Line 1\t\n
Line 2\n  
Line 3

2) Read content line by line

def readLinebyline():
    file = open('code2succeed.txt', 'r')
    for line in file.readlines():
        #can write code to parse the line
        print(line)       

if __name__ == '__main__':
    readLinebyline()

In above example, we follow below steps to read a file line by line.
Step 1: Open the file in read mode.

file = open('code2succeed.txt', 'r')

Step 2: Read content of file using file.readLines()method.
Step 3: print content of file line by line to console using for loop. Here, in the loop you can do any other operation like line parsing or anything else.

Output
Code2Succeed - Help You Grow
www.code2succeed.com\n
Help You Grow is main motto. Organized and well formatted approach of concepts and various examples.

Line 1\t\n
Line 2\n  
Line 3

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *