Reading and Writing Text Files
Reading and writing text files is a fundamental task in Python. In this section, we'll cover the essential operations for reading and writing text files.
1. Reading Text Files
To read the contents of a text file, you can use the open()
function with the mode 'r'
(read). You can then use methods like read()
, readline()
, or iterate through the file object to access the file's contents.
Using read()
# Opening a text file for reading
with open('example.txt', 'r') as file:
contents = file.read()
# Print the contents
print(contents)
Using readline()
# Opening a text file for reading
with open('example.txt', 'r') as file:
line = file.readline()
while line:
print(line)
line = file.readline()
Iterating Through Lines
# Opening a text file for reading
with open('example.txt', 'r') as file:
for line in file:
print(line)
2. Writing Text Files
To write text data to a file, use the open()
function with the mode 'w'
(write). You can then use the write()
method to add text to the file. Be cautious when writing to a file, as it will overwrite existing content.
# Opening a text file for writing
with open('output.txt', 'w') as file:
file.write('Hello, world!')
3. Appending to Text Files
To add text to the end of an existing text file, use the mode 'a'
(append) when opening the file.
# Opening a text file for appending
with open('existing_file.txt', 'a') as file:
file.write('This text will be added to the end of the file.')
4. Exception Handling
When working with files, it's good practice to use exception handling to manage errors, such as file not found or permission issues.
try:
with open('example.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("Permission denied to open the file.")
Understanding how to read and write text files, along with proper exception handling, is crucial for working with external data in your Python programs.