Skip to main content

2.5 - Input and Output (I/O) Handling

2.5.1 - Introduction to I/O Handling

Input and output (I/O) handling is crucial in programming for interacting with users and managing data. This guide covers standard I/O and file I/O in Python.


2.5.2 - Standard Input and Output

Standard input/output involves using built-in functions for data exchange with the user.

2.5.2.1 - Printing Output

The print() function displays output to the console.

print("Hello, world!")

2.5.2.2 - Reading Input

The input() function reads user input as a string.

name = input("Enter your name: ")
print("Hello, " + name + "!")

2.5.3 - File Input and Output

Python supports various file operations, including reading from and writing to files.

2.5.3.1 - Opening and Closing Files

Use the open() function to open a file, specifying the mode ('r', 'w', 'a'). Always close the file after operations.

file = open("example.txt", "r")
# Operations...
file.close()

2.5.3.2 - Reading from Files

Use read(), readline(), or a loop over the file object to read file content.

with open("example.txt", "r") as file:
for line in file:
print(line)

2.5.3.3 - Writing to Files

Use write() to add content to a file. To append, open the file in append mode ('a').

with open("example.txt", "a") as file:
file.write("New line of text.\n")

2.5.3.4 - Context Managers for File Handling

The with statement simplifies file operations by handling opening and closing files.

with open('filename.txt', 'r') as file:
contents = file.read()

2.5.3.5 - Error and Exception Handling in File Operations

Use try-except blocks to handle file-related errors like FileNotFoundError.

try:
with open('filename.txt') as file:
contents = file.read()
except FileNotFoundError:
print("File does not exist.")

2.5.3.6 - Working with File Contents

Analyze and process file contents, such as counting words or lines in text files.

with open('example.txt') as file:
contents = file.read()
words = contents.split()
num_words = len(words)
print(f"The file has {num_words} words.")

2.5.3.7 - JSON Data Handling

Use the json module to read from and write to JSON files, a common format for data storage.

import json

# Reading JSON
with open('data.json', 'r') as file:
data = json.load(file)

# Writing JSON
with open('data.json', 'w') as file:
json.dump(data, file)

2.5.3.8 - CSV File Handling

Handle CSV files using Python's csv module for data exchange.

import csv

# Reading CSV
with open('data.csv', 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)

# Writing CSV
with open('data.csv', 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(['name', 'age'])
csv_writer.writerow(['Alice', 30])

2.5.3.9 - XML File Handling

Manage XML files for web data and configuration using xml.etree.ElementTree.

import xml.etree.ElementTree as ET

# Parsing XML
tree = ET.parse('data.xml')
root = tree.getroot()

# Creating XML
root = ET.Element('data')
child = ET.SubElement(root, 'child')
child.text = 'Content'
tree = ET.ElementTree(root)
tree.write('new_data.xml')