In this course, we will take a deep dive into input and output methods using Python. Input and output are fundamental elements of programming languages, providing the functionality to read and write data. In Python, various methods can be used for input and output, each with its unique use cases.
Standard Input/Output
Python outputs data to the standard output (console) through the print()
function. This function is a basic way to display strings on the screen without additional specifications. The print()
function can also accept one or more pieces of data separated by commas and allows for various formats to be specified, including newline characters.
print("Hello, Python!") # Basic output
print("Name:", "Hong Gil Dong", "Age:", 25) # Output multiple items
Conversely, to receive standard input, the input()
function is used. It accepts user input as a string, enabling the design of dynamic programs. Data obtained using the input()
function is always stored as a string, so it is essential to convert it into the appropriate data type as needed.
name = input("Please enter your name: ") # User input
print("Hello,", name) # Output the received data
File I/O
File I/O refers to the method of storing data in files or reading data from files. In Python, the open()
function is used to open files, and data can be read and written using the methods of the file object. Files are typically opened in text mode but can also be opened in binary mode. File modes can be specified as read (‘r’), write (‘w’), append (‘a’), etc.
# Writing data to a file
with open("example.txt", "w") as file:
file.write("Hello, world!") # Write a string to the file
In the above example, the with
statement is used to open the file. The with
statement ensures that the file is opened, operations are performed, and the file is automatically closed afterward.
Here’s how to read data from a file:
# Reading data from a file
with open("example.txt", "r") as file:
content = file.read() # Read all content of the file
print(content)
Understanding File Modes
There are various modes that can be used when opening files in Python. Each mode determines how the file will be handled.
- r: Opens the file in read-only mode. An error occurs if the file does not exist.
- w: Opens the file in write-only mode. If the file already exists, it will be overwritten.
- a: Opens the file in append mode. If the file exists, data will be added at the end.
- r+: Opens the file in read/write mode. The file must exist.
- w+: Opens the file in read/write mode. If the file already exists, it will be overwritten.
- a+: Opens the file in read/append mode. If the file exists, data will be added at the end.
- b: Opens the file in binary mode.
Example: Reading Binary Files
When opening binary files (images, videos, etc.) instead of text files, Python provides powerful capabilities.
with open("example.jpg", "rb") as binary_file:
data = binary_file.read()
print("File size:", len(data), "bytes") # Output the file size in bytes
Advanced I/O Techniques
Advanced Python input/output features include advanced usage of processing files in specific ways. For instance, handling CSV files or reading JSON files can be considered an expanded form of input and output.
CSV File Handling
Using Python’s csv
module makes it easier to handle CSV files. CSV files are a simple file format that stores data separated by commas (`,`).
import csv
# Writing to a CSV file
with open("data.csv", "w", newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
writer.writerow(["Bob", 30])
# Reading from a CSV file
with open("data.csv", "r") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
JSON File Handling
JSON serves as a means to handle JavaScript object notation in Python. Python’s json
module provides functionality to convert JSON format into Python data types and vice versa.
import json
# Writing JSON data
data = {
"name": "Charlie",
"age": 35,
"city": "Seoul"
}
with open("data.json", "w") as jsonfile:
json.dump(data, jsonfile)
# Reading JSON data
with open("data.json", "r") as jsonfile:
data_loaded = json.load(jsonfile)
print(data_loaded)
NOTE: JSON and CSV are widely used for data exchange on the web. It is crucial to handle data in the correct format to minimize risks.
Character Encoding and Decoding
When performing input and output, it is important to properly set character encoding and decoding. Particularly in programs that support multiple languages, using UTF-8 is common.
# Writing a UTF-8 encoded file
with open("utf8_file.txt", "w", encoding="utf-8") as file:
file.write("Hello. This is a UTF-8 encoded file.")
# Reading a UTF-8 encoded file
with open("utf8_file.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
If encoding is not specified, Python will follow the default settings of the individual operating system. This can cause compatibility issues when using files on different systems. Therefore, it is always recommended to specify the encoding explicitly.
Conclusion
Python provides powerful and flexible input/output capabilities. The input/output process does not just end with displaying simple data on the screen or reading from files; it includes methods for reading and writing various formats of data. Understanding and handling standard input/output to file I/O, as well as file modes, are all essential skills.
Continue to practice various input/output methods and applications to expand your programming skills. In the next session, we will take a closer look at exception handling in Python. If you have any questions, feel free to leave a comment!