Handling Text Files in Python
Text file handling is an important aspect of programming, enabling developers to interact with stored data, manage logs, or process content efficiently. Python is a multi-purpose programming language and easier to learn. Because of the simple and powerful file I/O operations offered by Python, it makes handling text files straightforward. This blog post will walk you through the basics of text files handling in Python, including reading, writing, and appending data.
1. Opening a File
Python provides the open() function to open files, and it accepts two primary arguments: the file name and the mode. Common modes include:
- ‘r’ – Read (default mode; raises an error if the file doesn’t exist).
- ‘w’ – Write (creates a new file or overwrites an existing one).
- ‘a’ – Append (adds content to the end of the file).
- ‘r+’ – Read and write.
e.g.
file = open(‘test.txt’, ‘r’)
2. Reading Files
The read() method reads the entire content of a file as a single string. Alternatively, you can use readline() to read one line at a time or readlines() to get a list of lines.
e.g.
file = open('test.txt', 'r')
content = file.read()
print(content)
# Reading line by line: as file:
for line in file:
print(line.strip())
3. Writing to Files
Use the write() method to write strings to a file. Note that opening a file in ‘w’ mode overwrites its content.
e.g.
file = open('test.txt', 'w')
file.write("Hello, World!\n")
file.write("This is a new line.")
4. Appending to Files
To preserve existing content and add new data, open the file in ‘a’ mode.
e.g.
file = open('test.txt', 'a')
file.write("Appending a new line.\n")
file.write("Adding another line to demonstrate appending.\n")
5. Closing Files
When you’re done working with a file, it’s essential to close it to free up system resources. Using a with statement automatically closes the file for you.
e.g.
file = open('test.txt', 'r')
content = file.read()
file.close()
Or simply:
with open('test.txt', 'r') as file:
content = file.read()
6. Error Handling
To handle errors, such as a missing file, wrap your file operations in a try-except block.
e.g.
try:
file = open('nonexistent.txt', 'r')
content = file.read()
file.close()
except FileNotFoundError:
print("File not found.")
7. Working with File Paths
For better compatibility across operating systems, use the os or pathlib module.
e.g.
from pathlib import Path
file_path = Path("test.txt")
file = file_path.open('r')
content = file.read()
file.close()
Python’s file handling capabilities make it an excellent choice for working with text files. Whether you need to read, write, or append data, Python’s built-in functions and libraries simplify these tasks. Mastering text file handling is a valuable skill for any Python developer, as it lays the foundation for managing data efficiently in your projects.
Sample Example:
import os
#File name to check if it exists or not
file_name = "test.txt"
#Function to write text to file
def writeFile(text):
try:
f = open(file_name, "a")
f.write(text)
f.write("Add another line...\n")
except FileNotFoundError:
print("File not found error while writing to file....")
#Using os module, check if file exists or not. If already exists, print #message and write text to file by calling the function.
#If doesn't exist, then create file and write text to it by calling a #function.
if os.path.exists(file_name):
print("File Exists")
writeFile("Append text to an existing file\n")
else:
print("File doesn't exist. creating file.")
writeFile("Append text after creating file...\n")
Please visit our Blog page for to read more posts.
Disclaimer: This blog post is for informational purposes only and is provided as it is. Read Disclaimer