1. Reading from a Text File:
To read from a text file, you can use the open()
function to open the file in read mode (“r”). Here’s an example:
# Opening a text file for reading
with open("example.txt", "r") as file:
content = file.read()
print(content)
This reads the entire content of the file into a string.
Reading Lines:
You can also read the file line by line using a loop:
# Reading lines from a text file
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Use strip() to remove newline characters
2. Writing to a Text File:
To write to a text file, you can use the open()
function with the write mode (“w”). If the file already exists, it will be truncated. If it doesn’t exist, a new file will be created.
# Writing to a text file
with open("output.txt", "w") as file:
file.write("Hello, Python!\nThis is a new line.")
Appending to a Text File:
To append content to an existing file, use the append mode (“a”):
# Appending to a text file
with open("output.txt", "a") as file:
file.write("\nAppending additional content.")
3. Reading and Writing Modes:
You can combine both reading and writing modes by using the “r+” or “w+” modes. “r+” allows reading and writing, with the file pointer at the beginning. “w+” also allows reading and writing, but it truncates the file.
# Reading and writing to a text file
with open("example.txt", "r+") as file:
content = file.read()
print("Original content:", content)
# Writing new content
file.write("\nAdding new content.")
# Moving the file pointer to the beginning for reading
file.seek(0)
new_content = file.read()
print("New content:", new_content)
4. Using seek()
and tell()
:
The seek(offset, whence)
method is used to move the file pointer to a specified position. The tell()
method returns the current position of the file pointer.
with open("example.txt", "r") as file:
print("Initial position:", file.tell()) # Output: 0 (start of the file)
# Move to the 10th byte
file.seek(10)
print("Current position:", file.tell()) # Output: 10
content = file.read()
print("Content from position 10:", content)
5. Conclusion:
Reading and writing text files are common tasks in Python. Whether you’re processing data from external sources, logging information, or creating configuration files, mastering file handling is crucial for many programming scenarios.
In the next sections, we’ll explore more advanced topics and practical applications of file handling in Python.