Working with Files in Python: A Beginner’s Guide
One of Python’s most practical features is its ability to interact with files. Whether you're analyzing data, logging activity, or saving output, file handling is a fundamental skill. In this post, we’ll walk through everything you need to know to read, write, and manipulate files using Python.
What Are File Objects?
Python uses file objects to interact with external files. These can be:
-
Plain text files (
.txt
) -
Data files (like
.csv
,.json
) -
Media files
-
Documents (like
.pdf
,.docx
), etc.
For some file types, you’ll need to install additional modules—but for text files, Python's built-in functions will do just fine.
Creating a Test File (In Jupyter)
If you're working in Jupyter Notebook, you can quickly create a file using IPython magic:
%%writefile test.txt
Hello, this is a quick test file.
We are experimenting on files with new lines.
Introducing new lines again.
Another line.
This creates a new file test.txt
in your working directory.
Opening a File
Use Python’s built-in open()
function:
myfile = open('test.txt')
To read its content:
print(myfile.read())
To get lines as a list:
myfile.seek(0)
print(myfile.readlines())
Got an Error?
Check that:
-
The file is in the same directory as your script or notebook.
-
You're using the correct path.
File Paths
-
Windows: Use double backslashes
open("C:\\Users\\YourName\\Documents\\file.txt")
-
Mac/Linux: Use regular slashes
open("/Users/YourName/Documents/file.txt")
Reading Files and the File Pointer
When a file is read, Python moves a "cursor" to the end of the file. If you try reading again, it returns nothing. Reset it like this:
myfile.seek(0)
myfile.read()
Always close the file when you're done:
myfile.close()
Writing to a File
To write to a file, open it in write mode ('w'
). This will overwrite the file!
myfile = open('test.txt', 'w')
myfile.write("This is a new line")
myfile.close()
Use 'w+'
to both write and read:
myfile = open('test.txt', 'w+')
myfile.write("Writing and reading")
myfile.seek(0)
print(myfile.read())
myfile.close()
Appending to a File
To add to the end of a file without deleting the existing content, use append mode 'a'
:
myfile = open('test.txt', 'a+')
myfile.write("\nThis is appended text.")
myfile.close()
In Jupyter, you can use:
%%writefile -a test.txt
This is text being appended.
Another appended line.
Tip: Add a blank line before new content to avoid merging lines.
Iterating Through a File (Line-by-Line)
Use a for
loop to read the file line-by-line. This is more memory efficient than readlines()
.
with open('test.txt') as file:
for line in file:
print(line)
This approach:
-
Doesn’t load the whole file into memory
-
Automatically closes the file afterward
Best Practices for File Handling
-
Always close your files after reading or writing
-
Use
with open(...)
to automatically manage file closing -
Use
seek(0)
to reset the file pointer if needed -
Avoid using
read()
for very large files—prefer line-by-line reading