Text file handling is a fundamental skill in Python programming. This guide will cover how to open, read, write, and append text files.
To open a text file in Python, use the open() function. This function returns a file object, which allows you to read from or write to the file.
Syntax:
file_object = open(file_name, mode)
Example:
# Open a file for reading
file = open('example.txt', 'r')
There are several ways to read from a text file in Python:
2.1 read()
Reads the entire file as a single string.
Example:
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
2.2 readline()
Reads one line at a time.
Example:
file = open('example.txt', 'r')
line = file.readline()
while line:
print(line, end='') # Avoid adding extra newlines
line = file.readline()
file.close()
2.3 readlines()
Reads all lines and returns them as a list of strings.
Example:
file = open('example.txt', 'r')
lines = file.readlines()
for line in lines:
print(line, end='')
file.close()
You can write to a text file using the write() and writelines() methods.
3.1 write()
Writes a string to the file.
Example:
file = open('example.txt', 'w')
file.write('Hello, World!\n')
file.write('This is a test.\n')
file.close()
3.2 writelines()
Writes a list of strings to the file.
Example:
file = open('example.txt', 'w')
lines = ['Hello, World!\n', 'This is a test.\n']
file.writelines(lines)
file.close()
Appending data to an existing file can be done using the append mode 'a'.
Example:
file = open('example.txt', 'a')
file.write('Appending this line.\n')
file.close()
Using the with statement for file handling ensures that the file is properly closed after its suite finishes, even if an exception is raised.
Example:
# Reading with `with` statement
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Writing with `with` statement
with open('example.txt', 'w') as file:
file.write('Hello, World!\n')
file.write('This is a test.\n')
# Appending with `with` statement
with open('example.txt', 'a') as file:
file.write('Appending this line.\n')