Python File Handling Basics (Read and Write)
File handling in Python means working with files saved on your computer.
At the beginner level, this usually means:
- opening a file
- reading data from it
- writing data to it
- closing it safely
Python makes this simple with the built-in open() function. This page focuses on the core ideas only. If you need a specific task, such as reading line by line or checking whether a file exists, use the related guides in the See also section.
Quick example
The safest beginner pattern is to use with open(...). Python will close the file automatically when the block ends.
with open("example.txt", "w") as file:
file.write("Hello, file!\n")
with open("example.txt", "r") as file:
content = file.read()
print(content)
Expected output:
Hello, file!
In this example:
"w"opens the file for writingfile.write(...)saves text to the file"r"opens the file for readingfile.read()gets the file content as a string
What file handling means in Python
A file is data stored on your computer, such as:
- a
.txtfile - a
.csvfile - a log file
- a configuration file
File handling means:
- choosing a file
- opening it
- reading or writing data
- closing it when finished
Python uses the built-in open() function for this. If you want a full function guide, see Python open() function explained.
The basic file workflow
Most file code follows the same steps:
- Choose the file path you want to use.
- Open the file with
open(). - Pick a mode such as read or write.
- Use methods like
read()orwrite(). - Close the file, or use
withso it closes automatically.
A simple example:
with open("notes.txt", "w") as file:
file.write("Learn Python file handling")
This creates or replaces notes.txt and writes one line of text into it.
Understanding file modes
When you open a file, you choose a mode. The mode tells Python what you want to do with the file.
"r" read mode
Use "r" to read an existing file.
with open("notes.txt", "r") as file:
content = file.read()
print(content)
Important:
- the file must already exist
- if it does not exist, Python raises
FileNotFoundError
"w" write mode
Use "w" to write to a file.
with open("notes.txt", "w") as file:
file.write("New content")
Important:
- if the file does not exist, Python creates it
- if the file already exists, old content is erased
"a" append mode
Use "a" to add content to the end of a file.
with open("notes.txt", "a") as file:
file.write("\nAnother line")
Important:
- existing content stays
- new content is added at the end
If you want more practice with this, see How to append to a file in Python.
"x" create mode
Use "x" to create a brand-new file.
with open("new_file.txt", "x") as file:
file.write("Created for the first time")
Important:
- this fails if the file already exists
For beginner examples, text mode is usually enough. That is the default, so you do not need to add anything extra for normal text files.
Why use with open()
For beginners, with open() is the best pattern to learn first.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Why this is recommended:
- it closes the file automatically
- it helps prevent mistakes
- it keeps code shorter and cleaner
Without with, you would need to remember to call close() yourself:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
This works, but beginners often forget the last line. That is why most examples should use with open().
Reading from a file
Python gives you a few common ways to read file data.
Read the whole file with read()
Use read() when you want all the contents as one string.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Read one line with readline()
Use readline() when you want just one line at a time.
with open("example.txt", "r") as file:
first_line = file.readline()
print(first_line)
Read all lines with readlines()
Use readlines() when you want a list of lines.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Example output:
['First line\n', 'Second line\n']
Choose the method based on what you need:
read()→ one stringreadline()→ one linereadlines()→ list of lines
If your goal is a specific reading task, see How to read a file in Python or How to read a file line by line in Python.
Writing to a file
Use write() to save text into a file.
Write text in "w" mode
with open("output.txt", "w") as file:
file.write("Hello\n")
file.write("World\n")
This writes text to the file. If output.txt already had content, it is replaced.
Add text in "a" mode
with open("output.txt", "a") as file:
file.write("More text\n")
This adds new text after the existing content.
Writing numbers
write() only accepts strings. If you try to write a number directly, Python will raise an error.
Correct example:
score = 123
with open("score.txt", "w") as file:
file.write(str(score))
If you want a task-focused guide, see How to write to a file in Python.
What beginners should watch out for
These are some very common file mistakes:
- Using
"w"by mistake and erasing existing content - Trying to read a file that does not exist
- Using the wrong file path
- Trying to write a number without converting it to a string
- Trying to open a folder as if it were a file
Common causes
- Opening a file with the wrong mode
- Using an incorrect relative or absolute path
- Forgetting that
"w"overwrites existing content - Trying to write non-string data with
write() - Trying to open a file that does not exist
- Attempting to open a directory as if it were a file
Helpful debugging commands
If file code is not working, these quick checks often help:
print(content)
print(type(content))
import os
print(os.getcwd())
print(os.path.exists("example.txt"))
print(os.listdir())
What these do:
print(content)shows what you actually readprint(type(content))confirms the data typeos.getcwd()shows the current working folderos.path.exists("example.txt")checks whether the file existsos.listdir()shows files in the current folder
If Python says a file does not exist, see FileNotFoundError in Python: causes and fixes.
If the problem is really a path issue, Working with file paths in Python will help.
When to go to a more specific page
This page teaches the basic idea of file handling. Use a more specific page when you need to solve one task.
For example:
- read a file for a real task
- write data to a file
- append new content
- read line by line
- check whether a file exists
- fix a file-related error
FAQ
What is the easiest way to open a file in Python?
Use with open(...) as file:. It is simple and closes the file automatically.
What is the difference between "w" and "a" mode?
"w" replaces the file contents. "a" adds new content to the end.
Do I need to call close() every time?
Not if you use with open(). Python handles closing the file for you.
Why does Python say the file does not exist?
The file path may be wrong, or your script is running in a different folder than you expect.
Can write() save numbers directly?
No. Convert numbers to strings first, for example str(123).