Input and Output (I/O) in Python

Introduction

When working with Input and Output (I/O) in Python, handling user input, printing formatted output, and reading/writing files are essential skills. Python provides powerful I/O capabilities that make data interaction seamless.

In this guide, we’ll explore everything about Input and Output (I/O) in Python, including user input, console output, file handling, and best practices.

Input and Output (I/O) in Python

1. What is Input and Output (I/O) in Python?

Input and Output (I/O) in Python refers to the mechanisms for accepting data from users (input) and displaying or saving data (output).

  • Input: Receiving data from users using the input() function or reading from files.
  • Output: Displaying results using print() or writing to files.

2. Taking Input in Python

2.1 Using input() Function

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

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

2.2 Handling Numeric Input

Convert user input to integer or float:

age = int(input("Enter your age: "))  
print(f"You are {age} years old.")

2.3 Command-Line Arguments

Use the sys module to receive input from the command line.

import sys  
print("Arguments passed:", sys.argv)

3. Printing Output in Python

3.1 Using print() Function

print("Hello, World!")

3.2 Formatting Output with sep and end

print("Python", "I/O", "Tutorial", sep=" - ")  
print("End of", end=" Output Section.\n")

3.3 Using f-strings for Better Formatting

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

4. File Handling in Python – Reading and Writing Files

4.1 Opening a File

file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

4.2 Writing to a File

with open("output.txt", "w") as file:
    file.write("Python file handling made easy!")

4.3 Reading a File Line by Line

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

4.4 Appending to a File

with open("output.txt", "a") as file:
    file.write("\nAppending a new line.")

Learn: How to Get Project Management Skills: A Comprehensive Guide

5. Working with Different File Formats in Python

5.1 Handling CSV Files

import csv

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

5.2 Handling JSON Files

import json

data = {"name": "Alice", "age": 25}

with open("data.json", "w") as file:
    json.dump(data, file)

with open("data.json", "r") as file:
    loaded_data = json.load(file)
    print(loaded_data)

6. Advanced I/O Operations in Python

6.1 Redirecting Output to a File

import sys
sys.stdout = open("log.txt", "w")
print("This will be written to the file.")
sys.stdout.close()

6.2 Handling Binary Files

with open("image.jpg", "rb") as file:
    data = file.read()
    print("Bytes read:", len(data))

7. Exception Handling in Python I/O Operations

try:
    with open("non_existent.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found!")

8. Real-World Applications of Input and Output (I/O) in Python

8.1 Logging System

import logging

logging.basicConfig(filename="app.log", level=logging.INFO)
logging.info("This is an info message")

8.2 Web Scraping and Saving Data

import requests

response = requests.get("https://example.com")
with open("page.html", "w") as file:
    file.write(response.text)

Conclusion

Mastering Input and Output (I/O) in Python is crucial for any programmer. This guide covered:

✅ Taking user input using input() and command-line arguments.
✅ Displaying output using print() with formatting techniques.
✅ File handling – reading, writing, and appending data.
✅ Working with different file formats like CSV and JSON.
✅ Advanced I/O techniques including binary files and exception handling.

By applying these concepts, you’ll enhance your Python skills and build efficient applications.

Learn More:
Comments in Python: A Complete Guide

Leave a Comment