Python – Read a file example

Posted on

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.

1) Read content of the file.

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

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

Output

2) Read content line by line

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

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

Stay tuned for more updates and tutorials !!!

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.