No history yet

File Handling Basics

Working with Files

Think of a file on your computer like a notebook. Before you can read what's inside or write a new entry, you need to open it. When you're finished, you should close it to keep everything tidy. Python works the same way.

The primary tool for this is the open() function. It takes two main arguments: the file's name and the mode, which tells Python what you want to do with the file. After you're done, you use the close() method to shut the notebook.

File Modes

The mode you choose is crucial. It changes how Python interacts with the file. Let's look at the three most common ones.

Write Mode ('w'): Use this to write to a file. If the file doesn't exist, Python will create it for you. Be careful: if the file does exist, this mode will erase everything inside before writing the new content.

# Let's create a file and write a line to it.
f = open("diary.txt", "w")
f.write("I'm learning Python file handling.")
f.close() # Always remember to close the file!

Now you have a file named diary.txt with a single sentence in it.

Read Mode ('r'): This is for reading the contents of a file. It's the default mode, so if you don't specify one, Python assumes you want to read. If the file doesn't exist, you'll get an error.

# Now, let's read the file we just created.
f = open("diary.txt", "r")
content = f.read()
print(content)
f.close()

What if you want to add to a file without erasing it? That's where append mode comes in.

Append Mode ('a'): This mode lets you add content to the end of an existing file. If the file doesn't exist, Python will create it, just like with write mode.

# Let's add another line to our diary.
f = open("diary.txt", "a")
f.write("\nIt's pretty interesting.")
f.close()

The \n is a special character that creates a new line. If we read the file again, we'll see both sentences.

# Reading the updated file
f = open("diary.txt", "r")
print(f.read())
f.close()

A Better Way to Open Files

Manually calling close() works, but it has a weakness. If your program encounters an error after you open the file but before you close it, the file might be left open. This can cause problems.

Python has a cleaner, safer way to handle files using the with statement. It automatically closes the file for you, even if errors occur. Think of it as a helpful assistant who always remembers to shut the door behind you.

# Reading a file using the 'with' statement
with open("diary.txt", "r") as f:
    content = f.read()
    print(content)

# No f.close() needed! It's handled automatically.

When the code inside the with block is finished, the file is closed. This is the standard and recommended way to work with files in Python because it's simpler and more reliable.

Quiz Questions 1/5

What is the primary advantage of using the with open(...) as f: syntax over f = open(...) followed by f.close()?

Quiz Questions 2/5

You want to add a new entry to your diary.txt file without deleting what's already there. Which code snippet correctly opens the file in the right mode?