File Handling - CameronAuler/python-devops GitHub Wiki
Table of Contents
- File Modes
- Opening a File
- Reading a File
- Writing to a File
- Working with File Modes
- Handling File Exceptions
File Modes
Mode Identifier | Mode Description |
---|---|
"r" |
Read mode (default, file must exist). |
"w" |
Write mode (creates a new file or overwrites an existing file). |
"a" |
Append mode (adds data to an existing file). |
"x" |
Exclusive creation mode (fails if the files exists). |
"r+" |
Read and write mode (file must exist). |
"w+" |
Write and read mode (overwrites existing content). |
"a+" |
Append and read mode (adds new content while preserving existing content). |
Opening a File
Use the open()
function to open a file. The syntax is:
file = open("filename.txt", "mode")
NOTE: Replace "mode"
with a file mode (ex: "w"
).
Reading a File
Reading the Entire File
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Output:
Hello, this is an example file.
Reading Line by Line
This is especially useful for large files.
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Removes extra newlines
# Output:
Hello, this is an example file.
This is the second line.
Reading a Specific Number of Characters
Reads only the first n
characters from the file.
with open("example.txt", "r") as file:
content = file.read(10) # Reads first 10 characters
print(content)
# Output:
Hello, thi
Reading as a List of Lines
Reads all lines and stores them in a list.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
# Output:
['Hello, this is an example file.\n', 'This is the second line.\n']
Writing to a File
Writing a New File
Creates a new file or overwrites an existing file.
with open("output.txt", "w") as file:
file.write("Hello, this is a new file.\n")
file.write("This file will be overwritten if it exists.")
# output.txt content:
Hello, this is a new file.
This file will be overwritten if it exists.
Appending to an Existing File
Adds data to an existing file without overwriting.
with open("output.txt", "a") as file:
file.write("\nThis is an additional line.")
# output.txt content after running:
Hello, this is a new file.
This file will be overwritten if it exists.
This is an additional line.
Working with File Modes
"r+"
Mode (Read and Write)
Reads and writes to an existing file (file must exist).
with open("example.txt", "r+") as file:
content = file.read()
file.write("\nAppending new content while reading.")
# example.txt content after running:
Hello, this is an example file.
This is the second line.
Appending new content while reading.
"w+"
Mode (Write and Read)
Creates a new file or overwrites existing content.
with open("newfile.txt", "w+") as file:
file.write("This file is new.")
file.seek(0) # Move cursor back to start
print(file.read())
# Output:
This file is new.
"a+"
Mode (Append and Read)
Appends data while preserving existing content.
with open("example.txt", "a+") as file:
file.write("\nAdding a new line at the end.")
file.seek(0) # Move cursor back to start
print(file.read())
# Output (example.txt content after running):
Hello, this is an example file.
This is the second line.
Adding a new line at the end.
Handling File Exceptions
File Not Found
Errors
Handles cases where a file does not exist.
try:
with open("missing_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("Error: File not found.")
# Output:
Error: File not found.
Permission
Errors
Handles permission issues when trying to access restricted files.
try:
with open("/root/protected.txt", "w") as file:
file.write("Trying to write to a protected file.")
except PermissionError:
print("Error: You do not have permission to write to this file.")
# Output:
Error: You do not have permission to write to this file.
Using finally to Ensure File Closure
Ensures that a file is properly closed even if an error occurs.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found.")
finally:
file.close() # Ensures file is closed