This tutorial will guide you through the basics of file handling in Python. We will cover how to read, write, and manipulate files. Whether you are new to Python or looking to enhance your skills, this tutorial is for you.
Table of Contents
What is File Handling?
File handling in Python allows you to interact with files stored on your computer. You can read data from files, write data to files, and manipulate files in various ways.
Reading Files
To read a file in Python, you use the open()
function with the r
(read) mode. Here's an example of how to read a file:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing Files
Writing to a file in Python is similar to reading, but you use the w
(write) mode. If the file doesn't exist, it will be created. If it does exist, it will be overwritten.
with open('example.txt', 'w') as file:
file.write('Hello, World!')
File Modes
Python provides various file modes for different operations. Here are some common ones:
r
- Read modew
- Write modex
- Create modea
- Append modeb
- Binary modet
- Text mode (default)
Example Code
Here's an example that demonstrates reading and writing files:
# Writing to a file
with open('example.txt', 'w') as file:
file.write('This is a test file.')
# Reading from a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Further Reading
If you're looking to dive deeper into Python file handling, we recommend checking out our comprehensive guide on Advanced File Handling Techniques.
[center]