- Home
- /
- Python Read/Write Files
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python Read/Write Files
Read and Write Files in Python
Working with files is essential when you want to store or retrieve data between program runs. Python gives us easy ways to create, write to, read from, and append files.
Let’s explore how you can do all of that!
A. Creating a New File
To create a brand-new file, use the "x"
mode. This mode throws an error if the file already exists.
file = open("my_notes.txt", "x")
Output:
A file named my_notes.txt is created (with no content inside it).
B. Writing to a File
Use "w"
mode to write content to a file. If the file doesn’t exist, it creates it. If it does exist, it overwrites everything.
file = open("my_notes.txt", "w")
file.write("This is my first file using Python.")
file.close()
Content inside my_notes.txt:
This is my first file using Python.
If you write again in the same mode:
file = open("my_notes.txt", "w")
file.write("This will replace the previous content.")
file.close()
Updated content:
This will replace the previous content.
C. Reading from a File
Use "r"
mode to read the contents of a file. The file must already exist.
file = open("greeting.txt", "r")
print(file.read())
file.close()
Content inside greeting.txt
:
Hello from Learn With Arshyan!
You’ll see:
Hello from Learn With Arshyan!
D. Appending to a File
Use "a"
mode when you want to add content to the end of an existing file without deleting the previous data.
file = open("log.txt", "a")
file.write("Program started successfully.\n")
file.close()
Run again:
file = open("log.txt", "a")
file.write("Data was saved correctly.\n")
file.close()
Content inside log.txt
:
Program started successfully.
Data was saved correctly.
Final Tips
Always close your file with
.close()
after you’re done.Better practice: use
with open(...) as file:
which automatically closes the file for you.
with open("log.txt", "r") as file:
print(file.read())