Reading and Writing Text Files in Python
Text files are commonly used to store data in a readable format. Python provides straightforward methods to read from and write to text files. Let’s explore these functions and their applications.
Reading Data from Text Files
You can use the following functions to read data:
1. read()
Reads the entire content of the file as a single string.
with open("example.txt", "r") as file:
content = file.read()
print(content)
2. readline()
Reads one line at a time from the file.
with open("example.txt", "r") as file:
line = file.readline()
print(line)
3. readlines()
Reads all lines and returns them as a list of strings.
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing Data to Text Files
Python provides the write()
and writelines()
functions to write data to text files:
1. write()
Writes a single string to the file.
with open("example.txt", "w") as file:
file.write("Hello, Python learners!\n")
2. writelines()
Writes a list of strings to the file.
with open("example.txt", "w") as file:
file.writelines(["Line 1\n", "Line 2\n", "Line 3\n"])
Example: Combining Reading and Writing
Task: Read data from one file and write it to another file.
# Copying content from one file to another
with open("source.txt", "r") as source_file:
content = source_file.read()
with open("destination.txt", "w") as dest_file:
dest_file.write(content)
print("Content copied successfully!")
Try It Yourself
Problem 1: Count Lines in a File
Write a program to count the number of lines in a file using readlines()
.
Show Solution
with open("example.txt", "r") as file:
lines = file.readlines()
print("Number of lines:", len(lines))
Problem 2: Append Data to a File
Write a program to append a list of student names to an existing file.
Show Solution
students = ["Aditi\n", "Raj\n", "Neha\n"]
with open("students.txt", "a") as file:
file.writelines(students)
print("Student names added!")
By mastering these functions, you can efficiently read from and write to text files in Python. Practice frequently to build confidence!