Python Input and Output
Input and output operations allow your Python programs to interact with users and external data. This tutorial covers reading user input, displaying output, and working with files.
Console Output
The print() function displays information to the console.
Basic Printing
# Simple print
print("Hello, World!")
# Print multiple items
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
# Print with custom separator
print("Python", "is", "awesome", sep="-")
# Print without newline
print("Hello", end=" ")
print("World!")print() automatically adds newlines. Use sep and end for customization. See print() documentation.
Formatted Output
# f-strings (recommended)
name = "Alice"
age = 30
height = 5.6
print(f"Hello, {name}! You are {age} years old and {height} feet tall.")
# format() method
print("Hello, {}! Age: {}".format(name, age))
# % formatting (older style)
print("Hello, %s! Age: %d" % (name, age))
# Format numbers
price = 19.99
print(f"Price: ${price:.2f}")
print("Price: ${:.2f}".format(price))f-strings are the modern, preferred way for formatting. Learn about string formatting.
Console Input
The input() function reads user input from the console.
Basic Input
# Get user input
name = input("Enter your name: ")
print(f"Hello, {name}!")
# Input returns strings
age_str = input("Enter your age: ")
age = int(age_str) # Convert to integer
print(f"Next year you'll be {age + 1}.")input() always returns a string. Convert to other types as needed. See input() documentation.
Input Validation
def get_valid_age():
while True:
try:
age = int(input("Enter your age: "))
if age < 0:
print("Age cannot be negative. Try again.")
continue
if age > 150:
print("Please enter a realistic age.")
continue
return age
except ValueError:
print("Please enter a valid number.")
age = get_valid_age()
print(f"Your age is: {age}")Always validate user input to prevent errors. Use try-except for type conversion.
File Input/Output
Files allow data persistence beyond program execution.
Writing to Files
# Write text to file
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a text file.\n")
# Append to file
with open("example.txt", "a") as file:
file.write("Adding more text.\n")
# Write multiple lines
lines = ["Line 1", "Line 2", "Line 3"]
with open("lines.txt", "w") as file:
file.writelines(line + "\n" for line in lines)Use with statement for automatic file closing. Modes: ‘w’ (write), ‘a’ (append). See file modes.
Reading from Files
# Read entire file
with open("example.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Remove newline
# Read all lines into list
with open("example.txt", "r") as file:
lines = file.readlines()
print(f"File has {len(lines)} lines")
# Read specific number of characters
with open("example.txt", "r") as file:
chunk = file.read(10) # Read first 10 characters
print(chunk)Different methods for different reading needs. The with statement ensures files close properly.
File Paths
import os
# Current directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
# Join paths (cross-platform)
file_path = os.path.join("folder", "subfolder", "file.txt")
print(f"Full path: {file_path}")
# Check if file exists
exists = os.path.exists("example.txt")
print(f"File exists: {exists}")
# Get file info
if exists:
size = os.path.getsize("example.txt")
print(f"File size: {size} bytes")Use os.path for cross-platform path operations. See os.path documentation.
Working with CSV Files
CSV files store tabular data and are common for data exchange.
Writing CSV
import csv
# Sample data
data = [
["Name", "Age", "City"],
["Alice", 30, "New York"],
["Bob", 25, "Chicago"],
["Charlie", 35, "Los Angeles"]
]
# Write to CSV
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("CSV file created successfully!")Use the csv module for proper CSV handling. See csv documentation.
Reading CSV
import csv
# Read CSV file
with open("people.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
# Read into dictionary
with open("people.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['Name']} is {row['Age']} years old in {row['City']}")DictReader provides dictionary-like access to rows. Useful for data analysis.
JSON Data
JSON is a popular format for structured data exchange.
Writing JSON
import json
# Python data
data = {
"name": "Alice",
"age": 30,
"city": "New York",
"hobbies": ["reading", "coding", "hiking"]
}
# Write to JSON file
with open("person.json", "w") as file:
json.dump(data, file, indent=2)
print("JSON file created!")json.dump() converts Python objects to JSON. See json documentation.
Reading JSON
import json
# Read from JSON file
with open("person.json", "r") as file:
data = json.load(file)
print(f"Name: {data['name']}")
print(f"Hobbies: {', '.join(data['hobbies'])}")
# Parse JSON string
json_string = '{"name": "Bob", "age": 25}'
parsed = json.loads(json_string)
print(f"Parsed: {parsed}")json.load() converts JSON to Python objects. Use loads() for strings.
Binary Files
For non-text data like images or serialized objects.
Writing Binary Data
import pickle
# Python object
data = {
"numbers": [1, 2, 3, 4, 5],
"text": "Hello, binary world!"
}
# Serialize to binary file
with open("data.pkl", "wb") as file:
pickle.dump(data, file)
print("Binary file created!")pickle serializes Python objects. Use ‘wb’ mode for binary writing. See pickle documentation.
Reading Binary Data
import pickle
# Deserialize from binary file
with open("data.pkl", "rb") as file:
loaded_data = pickle.load(file)
print(f"Loaded: {loaded_data}")Use ‘rb’ mode for binary reading. Be careful with untrusted pickle files (security risk).
Error Handling
File operations can fail, so handle errors gracefully.
def safe_read_file(filename):
try:
with open(filename, "r") as file:
return file.read()
except FileNotFoundError:
return f"Error: File '{filename}' not found."
except PermissionError:
return f"Error: No permission to read '{filename}'."
except Exception as e:
return f"Error reading file: {e}"
content = safe_read_file("nonexistent.txt")
print(content)
# Check file before operations
import os
if os.path.exists("example.txt") and os.access("example.txt", os.R_OK):
with open("example.txt", "r") as file:
print(file.read())
else:
print("Cannot read file.")Always handle potential file errors. Use os.access() to check permissions.
Context Managers
The with statement ensures proper resource cleanup.
Custom Context Manager
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# Use custom context manager
with FileHandler("test.txt", "w") as file:
file.write("Hello from context manager!")
print("File automatically closed!")Implement __enter__ and __exit__ for custom context managers. See context managers.
Best Practices
- Always use
withstatements for file operations - Validate user input before processing
- Handle file operation errors gracefully
- Use appropriate file modes (‘r’, ‘w’, ‘a’, ‘rb’, ‘wb’)
- Close files explicitly if not using
with - Use
os.pathfor cross-platform path operations
External Resources:
Related Tutorials: