No history yet

File Handling

Working with Files

So far, all the data you've worked with has vanished the moment your program stops running. Variables, lists, and dictionaries are stored in memory, which is temporary. To save data permanently, you need to write it to a file. Think of a file as a container on your computer's hard drive for storing information long-term.

Python gives you simple tools to create, read, and update files. The first step is always the same: you have to open the file.

File handling is a powerful tool that allows us to manipulate files on a computer's file system using programming languages like Python.

The built-in open() function is your gateway to file operations. It takes two main arguments: the path to the file and the mode you want to open it in. The function returns a file object, which you can think of as a controller for the file. You'll use this object to perform all your actions.

file_object = open("filename.txt", "mode")

The mode is a string that tells Python what you plan to do. Are you reading, writing, or something else? Let's look at the most common modes.

ModeDescription
'r'Read (default). Opens the file for reading. Raises an error if the file doesn't exist.
'w'Write. Opens the file for writing. Creates the file if it doesn't exist, but erases all content if it does.
'a'Append. Opens the file for writing. Creates the file if it doesn't exist and adds new content to the end of the file.
'r+'Read and Write. Opens the file for both reading and writing. Raises an error if the file doesn't exist.

Choosing the right mode is critical. Using 'w' by mistake can wipe out an important file, so be careful!

Writing to Files

Let's create a new file and write some text to it. We'll open a file named journal.txt in write mode ('w'). If this file doesn't exist, Python will create it for us. If it does exist, its contents will be deleted before we write anything new.

We use the .write() method on the file object to add text. This method only accepts strings as input. After we're done, it's very important to close the file with the .close() method. Closing the file ensures that all your changes are saved and that the program releases its hold on the file.

# Open a file in write mode
file = open("journal.txt", "w")

# Write some lines to the file
file.write("This is my first journal entry.\n")
file.write("I am learning about file handling in Python.")

# Always close the file when you're done
file.close()

Notice the \n at the end of the first string. This is the newline character. Just like in print statements, you have to explicitly tell Python where to break lines in a file.

Now, what if you want to add to the file without deleting its contents? That's what append mode ('a') is for.

# Open the same file in append mode
file = open("journal.txt", "a")

# Append a new line
file.write("\nIt's pretty interesting!")

# Close the file
file.close()

If you open journal.txt now, you'll see all three lines of text.

Reading from Files

Once data is in a file, you need a way to get it back into your program. To do this, you'll open the file in read mode ('r'), which is the default mode if you don't specify one.

Python gives you a few ways to read a file's contents.

The .read() method reads the entire file and returns its content as a single string.

# Open the file in read mode
file = open("journal.txt", "r")

# Read the entire file's content
content = file.read()
print(content)

# Close the file
file.close()

This is simple, but it can be a problem for very large files, as it tries to load everything into memory at once.

Alternatively, you can read a file line by line, which is often more efficient. The .readline() method reads one line at a time, and .readlines() reads all lines and returns them as a list of strings.

# Read all lines into a list
file = open("journal.txt", "r")

lines_list = file.readlines()
print(lines_list)
# Output: ['This is my first journal entry.\n', 'I am learning about file handling in Python.\n', "It's pretty interesting!"]

file.close()

The most Pythonic way to read a file line by line is to loop directly over the file object. This approach is memory-efficient and clean.

# Loop over the file object
file = open("journal.txt", "r")

for line in file:
    # The print function adds its own newline, so we use .strip() 
    # to remove the newline character from the line we read
    print(line.strip()) 

file.close()

A Better Way to Open Files

Remembering to close every file you open is important, but it's also easy to forget. If your program encounters an error after a file is opened but before it's closed, the file might be left open.

Python provides a cleaner, safer way to handle files using the with statement. The with statement creates a temporary context for your file operations. When the block of code inside the with statement is finished, Python automatically closes the file for you, even if errors occur.

# Using 'with' to automatically handle closing the file
with open("journal.txt", "r") as file:
    for line in file:
        print(line.strip())

# The file is now automatically closed

This is the recommended way to work with files in Python. It's more concise and protects you from common mistakes. From now on, you should always use the with statement for file handling.

Quiz Questions 1/6

What is the primary purpose of Python's built-in open() function?

Quiz Questions 2/6

If you open an existing file in 'w' mode, its previous content will be erased.

File handling is a fundamental skill for any programmer. It allows your applications to save state, store user data, and interact with the world outside your program's memory.