Imagine storing information like your favorite recipes, a journal, or even game scores in a file. Python makes it simple to work with files so you can save data for later use or read data from existing files.
Opening and closing files in Python
To work with a file, you need to open it first. Python provides the open()
Example:
file = open("example.txt", "r") # Opens a file in read mode
file.close() # Always close a file after using it
Modes for opening files:
: Read (default)r
: Write (overwrites the file or creates it if it doesn't exist)w
: Append (adds to the file without overwriting)a
Reading from a file
You can read the contents of a file using the read()
Example:
file = open("example.txt", "r")
content = file.read()
print(content) # Displays the content of the file
file.close()
Writing to a file
To add text to a file, use the write()
Example:
file = open("example.txt", "w")
file.write("Hello, Python!") # Writes text to the file
file.close()
Safely handling files with with
with
Using with
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content) # The file is automatically closed after this block
Key takeaways
- Always close your files or use the
statement.with
- Use the correct file mode (
,r
,w
) depending on your task.a
- Reading and writing files is simple but powerful for real-world applications.