Kodeclik Logo

Our Programs

Courses

Gifting

Learn More

Schedule

Kodeclik Blog

Python Open File

Python can open files using built-in functions in a program. A file is stored in the computer and contains the data. A python program typically contains only the code needed to process data or content and they often read the data or content from a file. In this blogpost, you will see how to write a program in Python to open a file.

Creating a data file

First, let us create a simple data file containing months and seasons, like so:

January Winter
February Winter
March Spring
April Spring
May Spring
June Summer
July Summer
August Summer
September Fall
October Fall
November Fall
December Winter

Python file open

Let us name this file “seasons.txt”. Now we can open the file using the Python File Open:

f = open("seasons.txt", "r")
print(f.read())
f.close()

In the code below, the first line opens the file for reading (hence the “r” argument). This means that we are only going to use the file for input, not for output. The function open() returns a file object, in this case “f”. All future operations with this file are referred to using this file object.

The second line reads from the file using the read() function. The results of the read() are the entire contents of the file which we print using the print() function.

Once the file is processed, we close the file using the close() function. It is always good programming practice to close your files after you are done with all necessary operations on them.

Python file read and write

Python Open File

Note that the read() function reads the full content of the file in one go. This is fine if we do not require fine-grained access to individual lines or characters of the file.

If you desire to read the file line by line, you can use the readline() function.

f = open("seasons.txt", "r")
print(f.readline())
f.close()

Running the above program gives:

January Winter

Note that it prints an extra line - but there is no blank line in our file. Why?

This is because when it reads the line it reads the line along with the last character (which is the carriage return). When it prints it, remember print adds its own newline. This is why you get 2 newlines.

Try doing:

f = open("seasons.txt", "r")
print(f.readline())
print(f.readline())
f.close()

We get:

January Winter

February Winter

Reading files using a for loop

You can also loop through each line of the file instead of reading them all in one go.

f = open("seasons.txt", "r")
for x in f:
  print(x)
f.close()

This will yield:

January Winter

February Winter

March Spring

April Spring

May Spring

June Summer

July Summer

August Summer

September Fall

October Fall

November Fall

December Winter

We can also to take each line and print them in a different order:

f = open("seasons.txt", "r")
for x in f:
  y = x.split()
  print(y[1], y[0])
f.close()

This gives, as expected:

Winter January
Winter February
Spring March
Spring April
Spring May
Summer June
Summer July
Summer August
Fall September
Fall October
Fall November
Winter December

Reading files using readlines()

Just like readline() reads one line of the file at a time and returns a string, readlines() reads all lines of the file and returns a list of strings:

f = open("seasons.txt", "r")
lines = f.readlines()
print(lines)
f.close()

gives:

['January Winter\\n', 'February Winter\\n', 'March Spring\\n', 'April Spring\\n', 'May Spring\\n', 'June Summer\\n', 'July Summer\\n', 'August Summer\\n', 'September Fall\\n', 'October Fall\\n', 'November Fall\\n', 'December Winter']

Note that each line’s newline character is packaged as part of the string when reading that line (except the latd line which does not have a newline).

Reading a file that does not exist

Sometimes we might be reading from a file that does not exist. Let us make a spelling mistake in the name of our seasons file and see what happens.

f = open("season.txt", "r")
lines = f.readlines()
print(lines)
f.close()

gives:

Traceback (most recent call last):
File "main.py", line 1, in <module>
  f = open("season.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'season.txt'

As you can see we get a “no such file or directory” error. This is usually because Python is looking in the current directory for the file whereas the file might be residing in a different directory. You should give the full pathname whenever you attempt to read a file.

In general, it is good programming practice to trap for exceptions. We can use a “try except” block like so:

try:
  f = open("season.txt", "r")
  lines = f.readlines()
  print(lines)
  f.close()
except:
  print("Something went wrong")

This will yield:

Something went wrong

If the season.txt file does not exist.

Advanced File Handling in Python

For more complex file handling, such as working with databases or performing operations in web development frameworks, Python provides additional tools:

Working with MongoDB

When dealing with MongoDB, you often need to perform operations like creating databases, collections, and managing data. Python’s pymongo library is a valuable tool for this.

Create DB and Collection: Use db = client['mydatabase'] and collection = db['mycollection'] to create a database and collection.

Sort and Delete: Use methods like collection.find().sort() to sort documents and collection.delete_one() to delete documents.

Django Tutorial

In Django, file handling may involve reading and writing files uploaded by users or managing static files. Django provides tools for handling file uploads and storage, making it easier to integrate file operations into your web applications.

In this blogpost, you have learnt how to open a file, read its contents, and close the file. It is good programming practice to specify the full pathname of the file and also trap for exceptions. Now that you have learnt how to open and read a file, proceed onto our blogpost on how to write to files in Python! Also learn how to create directories programmatically in Python.

If you liked this blogpost, you will also find useful our blogpost on determining a file's size within Python. Also learn other ways to split a text file by lines in Python.

Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.