Python Course: Chapter 04 Input and Output of Python

This course covers the input/output (I/O) system in Python in detail. I/O plays an important role in controlling the flow of data, enabling interaction between the user and the program, as well as connections with the file system. This chapter will cover a variety of Python input/output mechanisms, from basic console input/output methods to handling files and exception handling.

1. Console Input/Output

1.1 print() function

The most commonly used function for outputting to the console in Python is the print() function. This function allows you to print various types of data to the standard output device.

print("Hello, World!")

The code above prints “Hello, World!” to the console. The print() function can take multiple arguments and, by default, adds a space between them when printing.

print("Hello,", "Python!")

The code above prints “Hello, Python!”. The print() function provides options to easily customize the default printing behavior. For example, you can change the delimiter between outputs and the end of the output.

print("Python", "Programming", sep="-", end="!")

The code above prints “Python-Programming!”. The sep parameter specifies the separator between outputs, while the end parameter specifies the string to append at the end of the output.

1.2 input() function

The input() function is used to receive user input from the standard input device. The string that the user enters in the console is returned when the input() function ends. By default, all input is received in the form of strings.

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

The code above prompts the user for their name and uses the entered name to output a greeting. If the entered data needs to be used as a numeric type, you must perform type conversion using the int() or float() functions.

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

The code above prompts for age input and uses it after converting to an integer.

2. File Input/Output

2.1 Opening a File

The way to open a file is by using the open() function. The open() function takes the filename and mode as arguments. The main modes are as follows:

  • 'r': Read mode
  • 'w': Write mode (overwrites existing file content)
  • 'a': Append mode (keeps existing content and adds new)
  • 'b': Binary mode (read/write binary files)

When a file is opened, a file object is created that allows file manipulation. Generally, after finishing file processing, you should call the close() method to close the file. This releases resources and prevents data loss.

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

The code above opens the example.txt file in read mode, reads the file content, and prints it. Finally, the close() method is used to close the file.

2.2 Reading a File

There are several methods to read the contents of a file, and the following are the most commonly used methods:

  • read(): Reads the entire content of the file as a single string.
  • readline(): Reads a single line from the file. This includes the newline character.
  • readlines(): Returns a list containing each line of the file as an element.
file = open("example.txt", 'r')
line = file.readline()
while line:
    print(line, end='')
    line = file.readline()
file.close()

The code above reads and prints the file line by line. It reads each line until reaching the end of the file using a while loop. Since the newline character is included, the end parameter of the print() function is set to an empty string.

2.3 Writing to a File

To write data to a file, it needs to be opened in ‘w’ or ‘a’ mode. The ‘w’ mode overwrites the content of the file, while the ‘a’ mode adds content to the end of the existing file.

file = open("example.txt", 'w')
file.write("This is a new line.\n")
file.write("Writing to files is easy.\n")
file.close()

The code above erases the existing content of the file and adds two new lines. When writing to a file, the write() method is used, and ‘\n’ is explicitly included for line breaks.

2.4 Using with Statement for File I/O

Using the with statement for file I/O makes the code cleaner and prevents mistakes by automatically closing the file.

with open("example.txt", 'r') as file:
    content = file.read()
    print(content)

The code above opens the file using the with statement, and the file is automatically closed when exiting the with block. This provides the advantage of not needing to explicitly call the close() method.

3. File Modes and Binary Files

Unlike text files, binary files must be read and written using the ‘b’ mode. This is used for manipulating binary data such as images, audio, and video files.

with open("image.jpg", 'rb') as binary_file:
    binary_content = binary_file.read()

The code above opens an image file in binary mode and reads its contents. Similarly, ‘wb’ mode is used for writing files.

4. Exception Handling

When dealing with files, various exceptions can occur, such as when a file does not exist or there are no read permissions. Handling these exceptions can prevent abnormal termination of the program.

try:
    file = open("nonexistent_file.txt", 'r')
except FileNotFoundError:
    print("The file does not exist.")
finally:
    file.close()

The code above handles the FileNotFoundError when a file does not exist, informing the user that the file is missing. The finally block executes regardless of whether an exception occurred and is where resource cleanup can take place if needed.

When using the with statement, file closing is handled automatically, making exception handling somewhat simpler.

Conclusion

In this chapter, we covered various methods for input and output in Python. From the basics of console input/output to file input/output and exception handling, we learned how to effectively input and output data using Python. Since these I/O functions are crucial in nearly all Python programs, more practice and utilization are necessary.

In upcoming lectures, more advanced topics will be covered, so make sure to thoroughly understand and practice the content presented in this chapter.