File operations in Python allow developers to interact with data in external files, enabling persistent storage, data transformation, and reporting. The two primary operationsβreading from and writing to filesβare crucial for building robust applications. In this guide, we will explore how to perform both reading and writing in a single program, understand different modes and practices, and look at real-world use cases where both actions are required together.
File handling refers to the process of reading data from and writing data to files. Python's built-in functions like open(), along with methods like read(), write(), and readlines(), provide all necessary capabilities for this.
Use 'r+' to read and modify existing files, 'w+' to clear and rewrite content, and 'a+' to preserve and extend existing content.
# Copy contents from source.txt to destination.txt
with open("source.txt", "r") as src, open("destination.txt", "w") as dest:
for line in src:
dest.write(line)
This example demonstrates how to open one file for reading and another for writing simultaneously using a single with statement. It reads each line from the source file and writes it into the destination file.
Suppose we have a file containing a list of user names. We want to read all names, convert them to uppercase, and save them back to the same file.
# Convert names to uppercase and rewrite file
with open("users.txt", "r") as file:
lines = file.readlines()
lines = [line.upper() for line in lines]
with open("users.txt", "w") as file:
file.writelines(lines)
It allows reading and writing without truncating the file. However, writing starts from the beginning of the file.
with open("sample.txt", "r+") as f:
content = f.read()
f.seek(0)
f.write(content.upper())
seek(0) resets the cursor to the beginning so that writing starts from the top of the file.
Filter out lines containing a specific keyword and write the rest to a new file.
with open("input.txt", "r") as infile, open("filtered.txt", "w") as outfile:
for line in infile:
if "ERROR" not in line:
outfile.write(line)
Read data from a file and log results to a separate file.
with open("data.txt", "r") as data, open("log.txt", "a") as log:
for line in data:
log.write(f"Processed line: {line}")
import csv
import json
data = []
with open("people.csv", "r") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
data.append(row)
with open("people.json", "w") as jsonfile:
json.dump(data, jsonfile, indent=4)
with open("config.txt", "r") as file:
lines = file.readlines()
lines[2] = "timeout=60\n"
with open("config.txt", "w") as file:
file.writelines(lines)
with open("bigfile.txt", "r") as infile, open("output.txt", "w") as outfile:
for line in infile:
if "Python" in line:
outfile.write(line)
read() loads the entire file into memory which can cause performance issues with large files. Use line iteration instead.
with open("image.jpg", "rb") as src, open("copy.jpg", "wb") as dest:
while chunk := src.read(1024):
dest.write(chunk)
Text mode can alter binary data like newline characters. Binary mode ensures byte-for-byte accuracy.
Always read content before opening the same file in write mode to avoid data loss.
try:
with open("unknown.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("File does not exist.")
Use with blocks to ensure automatic closing of files even if errors occur.
Read student grades from a CSV, calculate pass/fail, and write to a new report file.
import csv
with open("grades.csv", "r") as infile, open("report.csv", "w", newline='') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
writer.writerow(["Name", "Grade", "Status"])
for row in reader:
name, grade = row
status = "Pass" if int(grade) >= 50 else "Fail"
writer.writerow([name, grade, status])
import os
path = os.path.abspath("data.txt")
print("Opening file at:", path)
with open("process.log", "a") as log:
log.write("Successfully processed 1000 lines.\n")
Combining reading and writing in Python file handling is a common task in real-world software development. Whether you're transforming raw data into formatted reports, parsing logs, or creating backup copies, understanding the correct use of file modes, structure, and error handling is essential. With modes like r+, w+, and a+, and the power of Pythonβs built-in libraries, developers can create efficient, readable, and safe file-processing scripts.
From reading and modifying config files to processing structured datasets like CSV and JSON, mastering the ability to read from and write to files forms the foundation of data engineering and application development in Python.
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved