File Input/Output (I/O) allows your Python programs to interact with external files, reading data from them or writing data to them. This is crucial for persistence, logging, and data processing.
πΉ 1. Opening Files (
open())The
open() function is used to open a file. It returns a file object.Syntax:
file_object = open("filename.txt", "mode")
Common modes:
β’
"r": Read (default) - file must exist.β’
"w": Write - creates a new file or overwrites an existing one.β’
"a": Append - creates a new file or adds to the end of an existing one.β’
"x": Exclusive creation - creates a new file, fails if it exists.πΉ 2. Reading from Files
Once opened in read mode, you can read content:
β’
.read(): Reads the entire file content as a single string.β’
.readline(): Reads one line at a time.β’
.readlines(): Reads all lines into a list of strings.Example:
# Assuming 'data.txt' contains "Line 1\nLine 2\n"
file = open("data.txt", "r")
content = file.read()
print(content)
file.close() # Always close the file!
Output:
Line 1Line 2πΉ 3. Writing to Files
Once opened in write (
"w") or append ("a") mode, you can write content:β’
.write(string): Writes a string to the file. Remember to add \n for new lines.Example:
file = open("output.txt", "w")
file.write("Hello from Python!\n")
file.write("This is a new line.")
file.close()
(Creates/overwrites
output.txt with the text.)πΉ 4. The
with Statement (Best Practice!)The
with statement ensures files are automatically closed even if errors occur. This is the recommended way.Syntax:
with open("filename.txt", "mode") as file_object:
# perform file operations here
# File is automatically closed after this block
Example:python
with open("names.txt", "w") as f:
f.write("Alice\nBob\n")
with open("names.txt", "r") as f:
for line in f:
print(line.strip()) # .strip() removes newline characters
Output:
AliceBobπΉ 5. File Modes (Binary vs. Text)
β’ Text mode (default):
"r", "w", "a" - handles text encoding/decoding.β’ Binary mode:
"rb", "wb", "ab" - handles raw bytes, useful for images, executables, etc.Example (Binary Write):
with open("data.bin", "wb") as f:
f.write(b'\x01\x02\x03') # Writing bytes
π― Today's Goal
βοΈ Understand how to open files in different modes
βοΈ Read and write data to files
βοΈ Master the
with statement for safe file handling