Input Output Tutorial
TL;DR
Python provides multiple string formatting methods (f-strings, .format(), manual), file operations with context managers, and JSON serialization for data exchange.
Interesting!
F-strings can execute any Python expression inside the braces - you can even call functions and perform calculations right inside the string!
String Formatting Methods
python code snippet start
import math
name = "Alice"
age = 30
pi = math.pi
# F-strings (recommended) - Python 3.6+
message = f"Hello {name}, you are {age} years old"
precision = f"Pi is approximately {pi:.3f}"
calculation = f"2 + 2 = {2 + 2}"
# .format() method
message2 = "Hello {}, you are {} years old".format(name, age)
message3 = "Hello {name}, you are {age} years old".format(name=name, age=age)
indexed = "{0} and {1} and {0}".format("spam", "eggs") # spam and eggs and spam
# Manual formatting
number = "42"
padded = number.rjust(10) # Right-justify in 10 characters
centered = number.center(10) # Center in 10 characters
zeros = number.zfill(5) # Pad with zeros: 00042
python code snippet end
Advanced F-String Features
python code snippet start
# Format specifications
value = 1234.5678
print(f"{value:10.2f}") # Right-align, 2 decimal places
print(f"{value:<10.2f}") # Left-align
print(f"{value:^10.2f}") # Center-align
# Different number formats
number = 42
print(f"Decimal: {number:d}") # 42
print(f"Binary: {number:b}") # 101010
print(f"Octal: {number:o}") # 52
print(f"Hex: {number:x}") # 2a
print(f"Hex upper: {number:X}") # 2A
# Percentage and scientific notation
ratio = 0.875
print(f"Percentage: {ratio:.1%}") # 87.5%
large = 1234567.89
print(f"Scientific: {large:.2e}") # 1.23e+06
python code snippet end
File Operations
python code snippet start
# Writing to a file
with open('workfile.txt', 'w', encoding='utf-8') as f:
f.write('This is a test\n')
f.write('Hello, world!\n')
# Reading entire file
with open('workfile.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
# Reading line by line
with open('workfile.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip()) # Remove newline character
# Reading all lines into a list
with open('workfile.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(lines)
python code snippet end
Different File Modes
python code snippet start
# Text modes
with open('file.txt', 'r') as f: # Read
pass
with open('file.txt', 'w') as f: # Write (overwrites)
pass
with open('file.txt', 'a') as f: # Append
pass
# Binary modes
with open('image.jpg', 'rb') as f: # Read binary
data = f.read()
with open('output.jpg', 'wb') as f: # Write binary
f.write(data)
# Text mode with specific encoding
with open('unicode.txt', 'w', encoding='utf-8') as f:
f.write('Hello, δΈη! π')
python code snippet end
JSON Serialization
python code snippet start
import json
# Python data structures
data = {
'name': 'Alice',
'age': 30,
'languages': ['Python', 'JavaScript', 'Go'],
'active': True,
'balance': 123.45
}
# Convert to JSON string
json_string = json.dumps(data, indent=2)
print(json_string)
# Write JSON to file
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, indent=2)
# Read JSON from file
with open('data.json', 'r', encoding='utf-8') as f:
loaded_data = json.load(f)
print(loaded_data)
# Parse JSON string
parsed = json.loads(json_string)
print(parsed['name']) # Alice
python code snippet end
File Position and Seeking
python code snippet start
# Working with file positions
with open('workfile.txt', 'r+', encoding='utf-8') as f:
f.write('Hello, world!')
# Move to beginning
f.seek(0)
print(f.read()) # Read from beginning
# Check current position
print(f"Position: {f.tell()}")
# Move to specific position
f.seek(7) # Move to 7th character
f.write('Python!')
python code snippet end
Error Handling with Files
python code snippet start
try:
with open('nonexistent.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except IOError as e:
print(f"I/O error: {e}")
# Check if file exists before opening
import os
filename = 'data.txt'
if os.path.exists(filename):
with open(filename, 'r') as f:
print(f.read())
else:
print("File doesn't exist")
python code snippet end
Practical File Processing
python code snippet start
# Count lines, words, and characters
def analyze_file(filename):
try:
with open(filename, 'r', encoding='utf-8') as f:
lines = f.readlines()
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines)
char_count = sum(len(line) for line in lines)
return {
'lines': line_count,
'words': word_count,
'characters': char_count
}
except FileNotFoundError:
return None
# Usage
stats = analyze_file('example.txt')
if stats:
print(f"Lines: {stats['lines']}")
print(f"Words: {stats['words']}")
print(f"Characters: {stats['characters']}")
python code snippet end
CSV File Handling
python code snippet start
import csv
# Write CSV
data = [
['Name', 'Age', 'City'],
['Alice', '30', 'New York'],
['Bob', '25', 'Los Angeles'],
['Charlie', '35', 'Chicago']
]
with open('people.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(data)
# Read CSV
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
# CSV with DictReader/DictWriter
with open('people.csv', 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
print(f"{row['Name']} is {row['Age']} years old")
python code snippet end
Configuration Files
python code snippet start
import configparser
# Create config
config = configparser.ConfigParser()
config['DEFAULT'] = {
'ServerAliveInterval': '45',
'Compression': 'yes'
}
config['database'] = {
'host': 'localhost',
'port': '5432',
'name': 'myapp'
}
# Write config file
with open('config.ini', 'w') as f:
config.write(f)
# Read config file
config = configparser.ConfigParser()
config.read('config.ini')
print(config['database']['host']) # localhost
print(config.getint('database', 'port')) # 5432 (as integer)
python code snippet end
Python’s I/O capabilities handle everything from simple text files to complex data formats - always remember to use proper encoding and context managers for robust file operations!
Modern I/O benefits from f-string formatting , pathlib for path handling , and JSON serialization for comprehensive data management.
Reference: Input and Output