Dev In The Mountain Header
A Developer In The mountains having fun

Input and Output in Python

Input and output (I/O) operations allow your programs to interact with users, read data from files, and write results. This article covers the essential I/O operations in Python.

Standard Output with print()

The print() function displays output to the console.

Basic Printing

# Simple print
print("Hello, World!")

# Multiple items
print("Name:", "Alice", "Age:", 25)
# Output: Name: Alice Age: 25

# Print multiple lines
print("Line 1")
print("Line 2")
print("Line 3")

# Empty line
print()  # Prints a blank line

Print Parameters

# sep: Separator between items (default: space)
print("apple", "banana", "cherry", sep=", ")
# Output: apple, banana, cherry

print(2024, 1, 15, sep="-")
# Output: 2024-1-15

# end: What to print at the end (default: newline)
print("Loading", end="... ")
print("Done!")
# Output: Loading... Done!

# Print without newline
for i in range(5):
    print(i, end=" ")  # Output: 0 1 2 3 4 
print()  # New line

# file: Where to print (default: sys.stdout)
import sys
print("Error message", file=sys.stderr)

Formatting Output

# f-strings (Python 3.6+) - RECOMMENDED
name = "Alice"
age = 25
print(f"My name is {name} and I'm {age} years old")

# Expressions in f-strings
x = 10
y = 5
print(f"{x} + {y} = {x + y}")

# Format specifications
pi = 3.14159
print(f"Pi: {pi:.2f}")  # 2 decimal places: 3.14
print(f"Pi: {pi:.4f}")  # 4 decimal places: 3.14159

# Width and alignment
print(f"{'Left':<10}|")   # Left:     |
print(f"{'Center':^10}|")  # Center   |
print(f"{'Right':>10}|")   #     Right|

# Numbers with padding
print(f"{42:05d}")  # 00042

# Percentage
ratio = 0.751
print(f"Success rate: {ratio:.1%}")  # 75.1%

# Thousands separator
large = 1000000
print(f"Amount: {large:,}")  # 1,000,000

Legacy Formatting (Good to Know)

# str.format() - older but still common
print("Name: {}, Age: {}".format("Alice", 25))
print("Name: {0}, Age: {1}".format("Alice", 25))
print("Name: {name}, Age: {age}".format(name="Alice", age=25))

# % operator - very old, avoid in new code
print("Name: %s, Age: %d" % ("Alice", 25))

Standard Input with input()

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

Basic Input

# Read string
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Always returns a string!
age = input("Enter your age: ")
print(type(age))  # <class 'str'>

# Convert to other types
age = int(input("Enter your age: "))
print(type(age))  # <class 'int'>

height = float(input("Enter height in meters: "))
print(f"You are {height}m tall")

Input Validation

# Validate numeric input
while True:
    try:
        age = int(input("Enter your age: "))
        if 0 <= age <= 120:
            break
        else:
            print("Age must be between 0 and 120")
    except ValueError:
        print("Please enter a valid number")

print(f"Your age: {age}")

Multiple Inputs

# Split input string
text = input("Enter three numbers separated by spaces: ")
numbers = [int(x) for x in text.split()]
print(f"Sum: {sum(numbers)}")

# Example input: "10 20 30"
# Output: Sum: 60

# Unpack multiple values
data = input("Enter name and age (space-separated): ").split()
name, age = data[0], int(data[1])
print(f"{name} is {age} years old")

File I/O

Reading Files

# Method 1: Using 'with' (RECOMMENDED)
with open('data.txt', 'r') as file:
    content = file.read()
    print(content)
# File automatically closed after 'with' block

# Read entire file
with open('data.txt', 'r') as file:
    content = file.read()  # Returns entire file as string

# Read line by line
with open('data.txt', 'r') as file:
    for line in file:
        print(line.strip())  # strip() removes newline

# Read all lines into list
with open('data.txt', 'r') as file:
    lines = file.readlines()  # List of strings
    for line in lines:
        print(line.strip())

# Read specific number of lines
with open('data.txt', 'r') as file:
    line1 = file.readline()  # First line
    line2 = file.readline()  # Second line

Writing Files

# Write mode: Creates new or overwrites existing file
with open('output.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("Second line\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as file:
    file.writelines(lines)

# Append mode: Adds to existing file
with open('output.txt', 'a') as file:
    file.write("Appended line\n")

# Print to file
with open('output.txt', 'w') as file:
    print("Using print function", file=file)
    print("Second line", file=file)

File Modes

# Common modes:
# 'r'  - Read (default)
# 'w'  - Write (overwrites)
# 'a'  - Append
# 'x'  - Exclusive creation (fails if exists)
# 'b'  - Binary mode
# 't'  - Text mode (default)
# '+'  - Read and write

# Examples:
# 'rb'  - Read binary
# 'w+'  - Write and read
# 'ab'  - Append binary

Working with File Paths

import os
from pathlib import Path

# Check if file exists
if os.path.exists('data.txt'):
    print("File exists")

# Using pathlib (modern approach)
path = Path('data.txt')
if path.exists():
    print("File exists")
    print(f"Size: {path.stat().st_size} bytes")

# Create directory
Path('output').mkdir(exist_ok=True)

# Join paths
data_dir = Path('data')
file_path = data_dir / 'output.txt'

Practical Examples

Example 1: User Registration

def register_user():
    """Simple user registration with validation"""
    print("=== User Registration ===")
    
    # Get name
    while True:
        name = input("Full name: ").strip()
        if len(name) >= 2:
            break
        print("Name must be at least 2 characters")
    
    # Get age
    while True:
        try:
            age = int(input("Age: "))
            if 13 <= age <= 120:
                break
            print("Age must be between 13 and 120")
        except ValueError:
            print("Please enter a valid number")
    
    # Get email
    email = input("Email: ").strip().lower()
    
    # Confirm
    print("\n=== Confirm Registration ===")
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Email: {email}")
    
    confirm = input("\nConfirm? (yes/no): ").lower()
    if confirm == 'yes':
        # Save to file
        with open('users.txt', 'a') as file:
            file.write(f"{name},{age},{email}\n")
        print("Registration successful!")
    else:
        print("Registration cancelled")

# Run registration
register_user()

Example 2: Simple To-Do List

def todo_app():
    """Simple command-line to-do list"""
    todos = []
    
    while True:
        print("\n=== To-Do List ===")
        if todos:
            for i, task in enumerate(todos, 1):
                print(f"{i}. {task}")
        else:
            print("No tasks yet!")
        
        print("\nCommands: [a]dd, [d]one, [q]uit")
        choice = input("Choose: ").lower()
        
        if choice == 'a':
            task = input("New task: ").strip()
            if task:
                todos.append(task)
                print(f"Added: {task}")
        
        elif choice == 'd':
            if todos:
                try:
                    num = int(input("Task number: "))
                    if 1 <= num <= len(todos):
                        done = todos.pop(num - 1)
                        print(f"Completed: {done}")
                    else:
                        print("Invalid task number")
                except ValueError:
                    print("Enter a number")
            else:
                print("No tasks to complete")
        
        elif choice == 'q':
            # Save to file
            with open('todos.txt', 'w') as file:
                for task in todos:
                    file.write(f"{task}\n")
            print("Saved. Goodbye!")
            break

# Run app
todo_app()

Example 3: File Statistics

def file_stats(filename):
    """Analyze text file statistics"""
    try:
        with open(filename, 'r') as file:
            content = file.read()
        
        lines = content.split('\n')
        words = content.split()
        chars = len(content)
        
        print(f"=== File Statistics: {filename} ===")
        print(f"Lines: {len(lines)}")
        print(f"Words: {len(words)}")
        print(f"Characters: {chars}")
        
        if words:
            avg_word_len = sum(len(w) for w in words) / len(words)
            print(f"Average word length: {avg_word_len:.1f}")
        
    except FileNotFoundError:
        print(f"Error: {filename} not found")
    except Exception as e:
        print(f"Error: {e}")

# Example usage
file_stats('data.txt')

Example 4: CSV Data Reader

def read_csv(filename):
    """Read simple CSV file"""
    try:
        with open(filename, 'r') as file:
            # Read header
            header = file.readline().strip().split(',')
            
            # Read data rows
            data = []
            for line in file:
                values = line.strip().split(',')
                row = dict(zip(header, values))
                data.append(row)
        
        return data
    
    except FileNotFoundError:
        print(f"Error: {filename} not found")
        return []

# Create sample CSV
with open('people.csv', 'w') as f:
    f.write("name,age,city\n")
    f.write("Alice,25,NYC\n")
    f.write("Bob,30,LA\n")

# Read and display
people = read_csv('people.csv')
for person in people:
    print(f"{person['name']} is {person['age']} in {person['city']}")

Example 5: Configuration File

def save_config(settings, filename='config.txt'):
    """Save settings to file"""
    with open(filename, 'w') as file:
        for key, value in settings.items():
            file.write(f"{key}={value}\n")

def load_config(filename='config.txt'):
    """Load settings from file"""
    settings = {}
    try:
        with open(filename, 'r') as file:
            for line in file:
                line = line.strip()
                if line and '=' in line:
                    key, value = line.split('=', 1)
                    settings[key] = value
    except FileNotFoundError:
        pass
    return settings

# Example usage
config = {
    'username': 'alice',
    'theme': 'dark',
    'font_size': '12'
}

save_config(config)
loaded = load_config()
print(loaded)  # {'username': 'alice', 'theme': 'dark', ...}

Command-Line Arguments

import sys

# Access command-line arguments
# Script name is first argument
script_name = sys.argv[0]

# Additional arguments
if len(sys.argv) > 1:
    args = sys.argv[1:]
    print(f"Arguments: {args}")
else:
    print("No arguments provided")

# Example: python script.py arg1 arg2 arg3
# sys.argv = ['script.py', 'arg1', 'arg2', 'arg3']

Using argparse (Professional Way)

import argparse

def main():
    # Create parser
    parser = argparse.ArgumentParser(description='Process some data')
    
    # Add arguments
    parser.add_argument('input', help='Input file')
    parser.add_argument('output', help='Output file')
    parser.add_argument('--verbose', '-v', action='store_true',
                       help='Verbose output')
    parser.add_argument('--count', '-c', type=int, default=1,
                       help='Number of times')
    
    # Parse arguments
    args = parser.parse_args()
    
    # Use arguments
    print(f"Input: {args.input}")
    print(f"Output: {args.output}")
    print(f"Verbose: {args.verbose}")
    print(f"Count: {args.count}")

if __name__ == '__main__':
    main()

# Usage:
# python script.py input.txt output.txt
# python script.py input.txt output.txt --verbose --count 5

Error Handling with Files

# Handle file errors gracefully
def safe_read_file(filename):
    """Read file with error handling"""
    try:
        with open(filename, 'r') as file:
            return file.read()
    except FileNotFoundError:
        print(f"Error: {filename} not found")
        return None
    except PermissionError:
        print(f"Error: No permission to read {filename}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

# Use the function
content = safe_read_file('data.txt')
if content:
    print(content)

Common Patterns

Pattern 1: Process File Line by Line

# Memory efficient for large files
with open('large_file.txt', 'r') as file:
    for line in file:
        # Process one line at a time
        processed = line.strip().upper()
        print(processed)

Pattern 2: Backup Before Writing

import shutil
from pathlib import Path

def safe_write(filename, content):
    """Write with backup"""
    path = Path(filename)
    
    # Create backup if file exists
    if path.exists():
        backup = f"{filename}.bak"
        shutil.copy(filename, backup)
    
    # Write new content
    with open(filename, 'w') as file:
        file.write(content)

Pattern 3: Temporary Files

import tempfile

# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', delete=False) as temp:
    temp.write("Temporary data")
    temp_path = temp.name

print(f"Created temp file: {temp_path}")
# File persists after 'with' block (delete=False)

# Clean up when done
import os
os.remove(temp_path)

Common Mistakes

Mistake 1: Forgetting to Close Files

# WRONG: File not closed if error occurs
file = open('data.txt', 'r')
content = file.read()
file.close()  # Might not execute if error

# CORRECT: Always use 'with'
with open('data.txt', 'r') as file:
    content = file.read()
# Automatically closed

Mistake 2: Not Handling Non-Integer Input

# WRONG: Crashes on non-numeric input
age = int(input("Age: "))  # ValueError if user enters "abc"

# CORRECT: Validate input
try:
    age = int(input("Age: "))
except ValueError:
    print("Invalid number")
    age = None

Mistake 3: Overwriting Important Files

# DANGEROUS: 'w' mode destroys existing content
with open('important.txt', 'w') as file:  # Deletes content!
    file.write("New content")

# SAFER: Check first or use append
from pathlib import Path
if Path('important.txt').exists():
    print("Warning: File exists!")
    confirm = input("Overwrite? (yes/no): ")
    if confirm != 'yes':
        exit()

Practice Exercises

Exercise 1: Guest Book

Create a guest book program that asks for name and message, saves to file, displays all entries.

Exercise 2: Word Counter

Read text file and count occurrences of each word. Display top 10 most common.

Exercise 3: Number Processor

Read numbers from file (one per line), calculate sum, average, min, max. Write results to new file.

Sample Solutions

Exercise 1:

def guest_book():
    print("=== Guest Book ===")
    name = input("Your name: ")
    message = input("Your message: ")
    
    with open('guestbook.txt', 'a') as file:
        file.write(f"{name}: {message}\n")
    
    print("\n=== All Entries ===")
    with open('guestbook.txt', 'r') as file:
        print(file.read())

guest_book()

Exercise 2:

def word_counter(filename):
    with open(filename, 'r') as file:
        text = file.read().lower()
    
    # Count words
    words = text.split()
    counts = {}
    for word in words:
        counts[word] = counts.get(word, 0) + 1
    
    # Sort by count
    sorted_words = sorted(counts.items(), 
                         key=lambda x: x[1], 
                         reverse=True)
    
    # Display top 10
    print("Top 10 words:")
    for word, count in sorted_words[:10]:
        print(f"{word}: {count}")

word_counter('sample.txt')

Key Takeaways

  • print() displays output; customize with sep and end parameters
  • Use f-strings for modern string formatting: f"{variable}"
  • input() always returns a string; convert with int(), float(), etc.
  • Always use with statement for files (automatic closing)
  • File modes: 'r' (read), 'w' (write), 'a' (append)
  • Handle errors with try/except when reading user input
  • Path from pathlib is modern way to handle file paths
  • Process large files line-by-line for memory efficiency

What's Next?


Mastering I/O operations is essential for creating interactive programs and working with data!

More places to find me
Mental Health
follow me on Mastodon