Python Input/Output Operations
Overview
This lesson covers the basics of input and output (I/O) operations in Python, focusing on reading from and writing to the console and files. Understanding I/O is essential for creating interactive programs and handling data stored in files.
Introduction
Input/output operations are fundamental in programming, allowing your applications to interact with the outside world, whether through the console, files, or other data streams.
Console I/O
Reading Input
input()
Function: Used to read text input from the console. It pauses program execution and waits for the user to type something, followed by Enter.
name = input("What is your name? ")
print(f"Hello, {name}!")
Writing Output
print()
Function: Used to display information to the console. It can take multiple arguments, separated by commas, and supports formatting options.
print("This is a message.")
age = 25
print(f"You are {age} years old.")
File I/O
Opening Files
open()
Function: Opens a file and returns a file object. It requires the file path and a mode ('r'
for reading,'w'
for writing,'a'
for appending).
file = open('example.txt', 'r')
Reading from Files
- Methods:
read()
,readline()
, andreadlines()
.read()
reads the entire file.readline()
reads the next line.readlines()
reads all lines into a list.
content = file.read()
print(content)
file.close()
Writing to Files
- Methods:
write()
andwritelines()
.write()
writes a string to the file.writelines()
writes a list of strings.
file = open('example.txt', 'w')
file.write("Hello, world!")
file.close()
Closing Files
- Always close the file after completing operations using
close()
to free up system resources.
Using with
Statement
- The
with
statement ensures that the file is closed when the block is exited, even if an exception is raised.
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Best Practices
- Always use the
with
statement when dealing with file operations to ensure proper resource management. - Validate and sanitize input when reading from the console to avoid security issues or errors.
Conclusion
Input and output operations are the backbone of user interaction and data handling in Python. By mastering console and file I/O, you’ll be well-equipped to build a wide range of applications that can interact with users and work with data stored on disk.