WEEK 8: Reading and Writing Files - M199205zn/IAS-CS4 GitHub Wiki
Python provides built-in functions to read and write files, making file system manipulation straightforward. The open()
function is primarily used for handling files, allowing various modes such as reading, writing, and appending.
Before reading or writing a file, it must be opened using the open()
function.
file = open("example.txt", "r") # Open file in read mode
The open()
function takes two parameters:
-
Filename (e.g.,
"example.txt"
) -
Mode (e.g.,
"r"
for reading)
Mode | Description |
---|---|
"r" | Read mode (default); file must exist |
"w" | Write mode; creates file if it doesn’t exist, overwrites if it does |
"a" | Append mode; adds data to an existing file |
"r+" | Read and write mode |
"w+" | Read and write mode; overwrites file |
"a+" | Read and append mode |
To write to a file, use the "w"
or "a"
mode along with write()
or writelines()
.
with open("example.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a sample text file.")
-
write()
: Writes a single string to the file. -
writelines()
: Writes multiple lines from a list.
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
To read a file, use the "r"
mode with read()
, readline()
, or readlines()
.
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes extra spaces or newline characters
with open("example.txt", "r") as file:
first_line = file.readline() # Reads one line
all_lines = file.readlines() # Reads all lines into a list
To add data without overwriting, use "a"
mode.
with open("example.txt", "a") as file:
file.write("\nThis is a new line appended to the file.")
It is important to close a file after operations to free system resources. Using with open()
automatically handles this.
file = open("example.txt", "r")
content = file.read()
file.close() # Manually closing the file
However, using with open()
is the preferred approach since it automatically closes the file.
To avoid errors when opening a file, check if it exists using os.path.exists()
.
import os
if os.path.exists("example.txt"):
with open("example.txt", "r") as file:
print(file.read())
else:
print("File does not exist.")
Use the os
module to remove a file.
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted.")
else:
print("File not found.")
Python makes file handling simple with built-in functions for reading, writing, appending, and deleting files. Using with open()
ensures proper resource management. Understanding these basics is essential for working with file-based applications.
You can also make one involving structured data like JSON or CSV.