7.1 Reading and Writing Text Files in Python
Reading from and writing to files is a fundamental part of programming. Files are used to store data for long-term use and can be read or modified by your Python programs. Python makes it easy to work with files using built-in functions and the open()
function. In this section, we'll explore how to open, read, write, and close files in Python.
7.1.1 Opening Files with open()
The open()
function is used to open a file in Python. It returns a file object, which provides methods and attributes to interact with the file. You can open files in different modes depending on what you want to do with the file (read, write, append, etc.).
Basic Syntax:
file = open(filename, mode)
filename
: The name (and path, if necessary) of the file.mode
: The mode in which the file is opened (e.g., read, write, append). Common modes include:"r"
: Read (default mode). Opens the file for reading."w"
: Write. Opens the file for writing (overwrites the file if it exists or creates a new file)."a"
: Append. Opens the file for appending (adds new data at the end of the file)."r+"
: Read and write."w+"
: Write and read (overwrites the file if it exists or creates a new file).
7.1.2 Reading Files
When a file is opened in read mode ("r"
), you can use several methods to read the file’s content.
1. Reading the Entire File with read()
The read()
method reads the entire content of the file as a single string.
Example:
# Opening the file in read mode
file = open("example.txt", "r")
# Reading the entire file content
content = file.read()
print(content)
# Closing the file
file.close()
In this example:
- The
open("example.txt", "r")
opens the file in read mode. - The
read()
method reads all the text from the file. - It’s important to call
close()
after reading the file to free up system resources.
2. Reading Line by Line with readline()
The readline()
method reads one line at a time from the file.
Example:
file = open("example.txt", "r")
# Reading the file line by line
line = file.readline()
while line:
print(line.strip()) # strip() removes extra newline characters
line = file.readline()
file.close()
In this example:
- The
readline()
method reads one line from the file each time it is called. - The loop continues until no more lines are left to read.
3. Reading All Lines into a List with readlines()
The readlines()
method reads all lines from the file and returns them as a list of strings.
Example:
file = open("example.txt", "r")
# Reading all lines as a list of strings
lines = file.readlines()
for line in lines:
print(line.strip())
file.close()
In this example:
- The
readlines()
method stores each line as an element in a list. - You can then iterate over the list to process each line.
7.1.3 Writing to Files
When a file is opened in write mode ("w"
), you can use the write()
or writelines()
method to add content to the file. If the file already exists, opening it in write mode will overwrite the content. If it doesn’t exist, it will be created.
1. Writing with write()
The write()
method writes a string to the file.
Example:
# Opening the file in write mode
file = open("output.txt", "w")
# Writing a string to the file
file.write("Hello, World!\n")
file.write("This is a new line of text.\n")
# Closing the file
file.close()
In this example:
- The
write()
method writes text to the file. - The file is overwritten if it exists; otherwise, a new file is created.
2. Writing Multiple Lines with writelines()
The writelines()
method writes a list of strings to the file without adding newlines automatically.
Example:
lines = ["First line\n", "Second line\n", "Third line\n"]
# Opening the file in write mode
file = open("output.txt", "w")
# Writing multiple lines to the file
file.writelines(lines)
# Closing the file
file.close()
In this example:
- The
writelines()
method writes all the strings in the list to the file. - You must include the newline characters (
\n
) manually if you want lines to be separated.
7.1.4 Appending to Files
When a file is opened in append mode ("a"
), new data is added at the end of the file without overwriting the existing content.
Example:
# Opening the file in append mode
file = open("output.txt", "a")
# Appending new lines to the file
file.write("Appending new content to the file.\n")
file.write("This line will be added at the end.\n")
# Closing the file
file.close()
In this example:
- The
write()
method adds new content at the end of the file without erasing the existing content.
7.1.5 Using the with
Statement for File Handling
To ensure that files are properly closed after they have been used, it’s a good practice to use the with
statement when working with files. The with
statement automatically closes the file when the block of code is exited, even if an exception occurs.
Example:
# Using the with statement for reading a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # File is automatically closed when the block is exited
# Using the with statement for writing to a file
with open("output.txt", "w") as file:
file.write("This is written using the with statement.\n")
In this example:
- The
with
statement automatically handles closing the file, simplifying file management. - There’s no need to call
close()
explicitly, as the file is closed once the block ends.
7.1.6 Handling File Exceptions
When working with files, you may encounter errors if the file doesn’t exist, there’s a permission issue, or another file-related issue arises. You can handle these exceptions using try-except blocks.
Example:
try:
with open("nonexistent_file.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
except IOError:
print("An IOError occurred.")
In this example:
- A
FileNotFoundError
is caught if the file doesn’t exist. - Other I/O errors are caught by
IOError
, which could include permission issues or file corruption.
7.1.7 Working with File Paths
In Python, you can specify file paths to work with files stored in different directories. You can use either absolute paths or relative paths.
Example:
# Absolute path (specifies the full path)
file = open("/Users/username/Documents/example.txt", "r")
# Relative path (relative to the current working directory)
file = open("example.txt", "r")
Python also provides the os
and pathlib
modules to work with file paths more flexibly, allowing you to handle cross-platform file paths or manipulate file directories.
Example Using pathlib
:
from pathlib import Path
# Defining a file path using pathlib
file_path = Path("example.txt")
# Opening the file using pathlib
with file_path.open("r") as file:
content = file.read()
print(content)
7.1.8 Summary
- Opening files: Use the
open()
function with different modes to open a file (e.g., read, write, append). - Reading files: Use methods like
read()
,readline()
, orreadlines()
to read file content. - Writing files: Use
write()
orwritelines()
to add content to a file. Be careful, as opening a file in write mode ("w"
) will overwrite its content. - Appending files: Use the append mode (
"a"
) to add content without overwriting the existing data. - Using
with
: Thewith
statement automatically closes the file after use, ensuring safe file handling. - Handling exceptions: Use try-except blocks to catch errors such as
FileNotFoundError
andIOError
. - File paths: You can use absolute or relative paths, and the
pathlib
module
can simplify path handling.
Reading from and writing to files is a fundamental skill in Python programming, enabling you to store and retrieve data efficiently. Understanding how to handle files properly will help you build robust applications that manage data input and output securely and reliably.