You know how to get input from a user with input or argv. Now you will learn about reading file. You may have to play with this exercise the most to understand what’s going on, so do the exercise carefully and remember your checks. Working with files is an easy way to erase your work if you are not careful.

This exercise involves writing two files. One is the usual .py file that you will run, but the other is named sample.txt. This second file isn’t a script but a plain text file we’ll be reading in our script. Here are the contents of that file:

This is first line of file.
This is 2nd line..
I think I run out of Ideas to write a sample file
May be you can write a better one.

For reading a file we need to “open” that file in our script and assign it to a variable. We can use that variable as needed like print it out, or change the data to create new file. Let’s check an example where we will open file sample.txt and assign it to variable nameĀ sample_file then we will read that file and print it.

sample_file = open("sample.txt")
print (

Yes it is as easy as it look, Just 2 line code to read a file and print output. Now run the file, make sure that you have sample.txt file in same folder as this .py file. If you are using different location of .txt file then provide complete path of file.

Reading file using python -

It do exactly as we needed. Lets understand the code. In first line we opened a file named “sample.txt” and assigned it to sample_file variable. Now with help of this variable we can perform action on sample.txt file. In 2nd line we asked sample_file variable to read the file and used print function to print it.

I want you to try this code first and then move to next one.

Possible error

Very first possible error is location of file, Try to get this error so that in future if you get this error you will understand just use wrong name of file in your code and you will get same error.

Reading file with input

You can use input or argv function (if you don’t know this function, then I suggest you to read my previous chapter). Check below code.

print ("Enter file name to read")
name = input(">")
sample_file = open(name)
print (

While running this code you need to give exact file name i.e sample.txt if you give filename as “sample” then your code will throw error.

Exercise of the day

Try reading file by passing argv.

Try using escape character in txt file and see the result in output.

no comments

Leave me comment