Python File Handling

File handling in Python lets your programs create, open, read, and update files stored on disk, all through the built-in open function.

Working with files in Python

Programs often need to keep data around after they stop running, and files are the simplest way to do that. Python provides a built-in function called open that connects your code to a file on disk and returns a file object. Through that object you can read what a file contains or write new content into it. Every interaction begins by opening the file with a name and a mode, and ends by closing it so the operating system can release it.

File modes

The second argument to open is the mode, a short string that tells Python what you intend to do with the file. The mode also decides what happens if the file already exists or is missing, so choosing the right one matters.

ModeMeaning
"r"Read. Opens an existing file for reading; errors if it does not exist.
"w"Write. Creates a new file or empties an existing one before writing.
"a"Append. Adds new content to the end without erasing what is there.
"x"Create. Makes a new file and errors if it already exists.
"r+"Read and write on an existing file without truncating it.

You can also add a character for the data type. A "t" means text mode, which is the default and works with strings, while "b" means binary mode and works with raw bytes, useful for images or other non-text files.

Opening and closing a file

The most direct approach is to call open, work with the returned object, then call close. Closing is important because unflushed data may not reach the disk until it happens, and open files consume system resources.

Opening and closing manually

f = open("notes.txt", "w")
f.write("First line of notes\n")
f.close()

print("File saved and closed")

The with statement

Remembering to call close every time is error prone, especially when an exception interrupts your code. The recommended pattern is the with statement, which opens the file and closes it automatically as soon as the block finishes, even if an error is raised inside it.

Preferred pattern using with

with open("notes.txt", "w") as f:
    f.write("Written safely inside a with block\n")

# The file is already closed here
print("Done")
Note: Use the with statement for almost all file work. It guarantees the file closes properly and keeps your code shorter and clearer.
  • Choose the mode carefully, since "w" erases existing content while "a" preserves it.
  • Pass encoding="utf-8" to open when you work with text so characters are read and written consistently.
  • Prefer the with statement so files always close, even when errors occur.
  • Wrap file operations in try and except to handle a missing file or permission problem.
Note: Opening an existing file in "w" mode empties it immediately, before you write anything. If you meant to add to the file rather than replace it, use "a" instead.

Exercise: Python File Handling

What happens when you open an existing file using mode "w"?