Python Input and Output

Python’s input and output (I/O) functions provide ways to interact with external data, such as files, the console, and more. This guide covers fundamental I/O operations including reading and writing files, user input, error handling, and working with different file types.

1. Basic Console I/O

Python provides two functions for basic console I/O:

- input(): Reads a line of text from the user.
- print(): Writes a line of text to the console.
# Getting user input
user_name = input("Enter your name: ")
print("Hello,", user_name)

Example Output:

Enter your name: Alice
Hello, Alice
Explanation: input() reads a string from the user, and print() outputs text to the console.

2. Opening and Closing Files

The open() function is used to work with files. It accepts two main arguments:

1. Filename: The file’s name or path.
2. Mode: The file access mode, e.g., 'r' (read), 'w' (write), 'a' (append), or 'b' (binary mode).

# Opening and closing a file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
Explanation: The open() function opens a file in write mode, write() writes a line to it, and close() closes the file.

3. Reading from a File

Reading can be done in three main ways:

- read(): Reads the entire file.
- readline(): Reads one line at a time.
- readlines(): Reads all lines and returns them as a list.

# Writing sample content to the file for reading
with open("sample.txt", "w") as file:
    file.write("Line 1\nLine 2\nLine 3")

# Reading entire content
with open("sample.txt", "r") as file:
    content = file.read()
    print("Full Content:", content)

# Reading line-by-line
with open("sample.txt", "r") as file:
    print("First Line:", file.readline().strip())
    print("Second Line:", file.readline().strip())

# Reading all lines into a list
with open("sample.txt", "r") as file:
    lines = file.readlines()
    print("Lines List:", [line.strip() for line in lines])

Output:

Full Content: Line 1
Line 2
Line 3
First Line: Line 1
Second Line: Line 2
Lines List: ['Line 1', 'Line 2', 'Line 3']
Explanation: Each reading method provides a different way to read data depending on the requirements.

4. Writing to a File

Using write() to write a single line and writelines() to write multiple lines at once.
# Writing a single line
with open("output.txt", "w") as file:
    file.write("This is a single line.\n")

# Writing multiple lines
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as file:
    file.writelines(lines)

# Reading the written content for verification
with open("output.txt", "r") as file:
    print(file.read())

Output:

First line
Second line
Third line
Explanation: writelines() adds each element in lines to the file, while write() is used for individual lines.

5. File Modes

File access modes control how files are opened and modified. Here are the most common modes:

- 'r': Read (default).
- 'w': Write (overwrites).
- 'a': Append.
- 'b': Binary mode.

Example of append mode:
# Appending to a file
with open("output.txt", "a") as file:
    file.write("This is an appended line.\n")

# Reading the updated file
with open("output.txt", "r") as file:
    print(file.read())

Output:

First line
Second line
Third line
This is an appended line.
Explanation: The 'a' mode adds new content to the file without overwriting existing data.

6. Working with Binary Files

To read and write binary files (such as images), use the 'b' mode with 'rb' or 'wb'.
# Copying an image in binary mode
with open("source_image.jpg", "rb") as src:
    with open("copy_image.jpg", "wb") as dst:
        dst.write(src.read())
Explanation: The 'rb' and 'wb' modes are used for binary files to ensure byte-for-byte copying.

7. Using with for Context Management

Using with simplifies file handling by automatically closing the file, even if an exception occurs.
with open("example.txt", "w") as file:
    file.write("Hello, World!")  # File will close automatically here
Explanation: The with statement handles cleanup, closing the file at the end of the block.

8. File Positioning with seek() and tell()

seek() sets the file's current position, while tell() returns the current position.
# Writing and then using seek and tell
with open("position.txt", "w+") as file:
    file.write("Hello, World!")
    file.seek(0)  # Move to the start of the file
    print("Position after seek:", file.tell())
    print("Content:", file.read())

Output:

Position after seek: 0
Content: Hello, World!
Explanation: seek(0) moves to the start of the file. tell() verifies the current position.

9. Error Handling with Files

It’s essential to handle errors during file operations to prevent unexpected crashes. Using try-except ensures that exceptions are caught.
try:
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("File not found. Please check the filename.")

Output:

File not found. Please check the filename.
Explanation: FileNotFoundError is raised if the file doesn’t exist. The error is caught, and a message is displayed.

10. Reading and Writing CSV Files

Using the csv module for reading and writing CSV (Comma-Separated Values) files:
import csv

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

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

Output:

['Name', 'Age']
['Alice', '30']
['Bob', '25']
Explanation: The csv.writer() and csv.reader() handle CSV data efficiently.

Summary

Python’s I/O operations are versatile, providing methods to handle text, binary, and structured data. By mastering these I/O operations, you can manage data efficiently and handle errors gracefully in any application.

Previous: Multiprocessing | Next: Python os module

<
>