How to Read Files With Python

This blog post will show how to read files with Python built-in functions.


Working with files and content is something that Python knows how to handle very easily and allow developers to be very creative.


In the following examples, I have a code the I am passing a file as an argument (example #1). To read the file content, I use the open function to read the file and the read function to print the actual content.

from sys import argv
script, myfile = argv
txt = open (myfile)  
print ( 

If you prefer not to pass the file as an argument, you can use the following code.

from sys import argv
txt = open ("")
print (   

In the above two examples, I used the close option to close the file after opening and reading the file. This operation is important and allows Python to release the file after using it.

Note: To read just one line of the file using use print (txt.readline()) 

1 comment

Leave a comment

Your email address will not be published.