File handling is an important part of Python. It allows you to read data from files, create new files, and save information for later use.
Let's see how it works step by step.
Opening a File
The open() function is used to open a file.
It mainly takes two things:
- File name: The name of the file.
- Mode: Tells Python what you want to do with the file, such as read or write.
For example:
f = open('myfile.txt', 'r')This opens myfile.txt in read mode.
File Open Modes
| Mode | Description |
|---|---|
'r' |
Opens a file for reading. This is the default mode. An error is raised if the file doesn't exist. |
'w' |
Opens a file for writing. Creates the file if it doesn't exist and replaces its existing content if it does. |
'a' |
Opens a file for adding content at the end. Creates the file if it doesn't exist. |
'x' |
Creates a new file. An error is raised if the file already exists. |
't' |
Opens the file in text mode. This is the default mode. |
'b' |
Opens the file in binary mode, which is useful for files such as images and videos. |
You can also combine modes. For example, rb means read a file in binary mode.
Reading from a File
Once you open a file for reading, Python gives you several ways to read its contents.
read()
read() reads the entire file and returns its content as a string.
with open('myfile.txt', 'r') as f:
content = f.read()
print(content)readline()
readline() reads one line at a time.
with open('myfile.txt', 'r') as f:
line = f.readline()
print(line)You can call readline() again to read the next line.
readlines()
readlines() reads all the lines and returns them as a list.
with open('myfile.txt', 'r') as f:
lines = f.readlines()
print(lines)For example, if the file contains:
Line 1
Line 2
Line 3readlines() returns something like:
["Line 1\n", "Line 2\n", "Line 3\n"]Writing to a File
You can use write() to add content to a file.
with open('myfile.txt', 'w') as f:
f.write('Hello, world!')Because we're using "w" mode, any existing content in the file will be replaced.
If you want to add content without replacing what's already there, use "a" mode instead. We'll look at that below.
writelines()
writelines() can write multiple strings to a file.
lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']
with open('myfile.txt', 'w') as f:
f.writelines(lines)Notice the \n at the end of each string.
writelines() does not automatically add new lines, so you need to add \n yourself when needed.
Using print() to Write to a File
You can use print() function's file parameter to send the output to a file instead of the screen.
with open("output.txt", "w") as f:
print("Hello, World!", file=f)Instead of displaying the text in the terminal, Python writes it to output.txt.
You can also use other print() parameters:
with open("output.txt", "w") as f:
print("Hello", "World", sep=", ", file=f)The file parameter is useful when you want to save printed output to a file.
Flushing Output
When Python writes output, it may temporarily keep it in memory before actually sending it to its destination.
You can use flush=True with print() when you want Python to send the output immediately.
For example:
with open("output.txt", "w") as f:
print("Hello, World!", file=f, flush=True)You usually won't need flush=True for simple file operations.
It becomes more useful when working with things like real-time output, logs, or long-running programs.
Appending to a File
Sometimes you don't want to replace the existing content. You simply want to add something to the end of the file.
That's when you use "a" mode.
with open("myfile.txt", "a") as f:
f.write("This will be added to the end.\n")If the file already contains:
Helloit will now contain:
Hello
This will be added to the end.Closing a File
When you open a file manually, you should close it when you're finished.
You can use close():
f = open('myfile.txt', 'r')
# Do something with the file
f.close()But there's an easier and safer way: use the with statement.
with open('myfile.txt', 'r') as f:
content = f.read()Python automatically closes the file when the with block ends.
As a general rule, prefer using with when working with files.
File Position: seek() and tell()
Python keeps track of your current position in a file.
tell()
tell() tells you the current position.
with open("myfile.txt", "r") as f:
print(f.tell())seek()
seek() lets you move to a different position in the file.
with open("myfile.txt", "r") as f:
f.seek(5)
data = f.read()
print(data)This moves the file position before reading again.
For text files, it's better to think of seek() as moving to a different position in the file rather than always thinking in terms of characters, because the exact behavior can depend on the file and encoding.
Truncating a File with truncate()
truncate() is used to shorten a file.
For example:
with open('myfile.txt', 'w') as f:
f.write('Hello World!')
f.truncate(5) The file will contain:
HelloBe careful with truncate() because it permanently changes the file.
Best Practices
Here are a few things to remember when working with files:
- Use
withso Python automatically closes the file. - Choose the right mode (
r,w, ora) to avoid accidentally replacing your data. - Be careful with
wmode because it replaces existing content. - Use
flush=Trueonly when you actually need immediate output. - Be careful with file paths and make sure your program has permission to access the file.
👉 Next tutorial: Python Virtual Environment