File handling is a crucial aspect of programming that allows us to read from and write to files on the disk. Python provides built-in functions and methods for working with files, enabling us to perform various operations such as reading, writing, appending, and modifying file content.

Let’s explore file handling in Python:

# Opening a file in different modes
# "r" - Read mode (default)
# "w" - Write mode (overwrites existing file or creates a new file)
# "a" - Append mode (appends content to the end of the file)
# "x" - Exclusive creation mode (creates a new file but raises an error if it already exists)
# "b" - Binary mode
# "t" - Text mode (default)

# Writing to a file
with open("myfile.txt", "w") as file:
    file.write("Hello, world!")

# Reading from a file
with open("myfile.txt", "r") as file:
    content = file.read()
    print("File content:", content)

# Appending to a file
with open("myfile.txt", "a") as file:
    file.write("\nAppending new content!")

# Reading line by line
with open("myfile.txt", "r") as file:
    lines = file.readlines()
    print("File lines:")
    for line in lines:
        print(line.strip())

# Closing a file automatically with "with" statement

# Working with binary files
with open("myimage.jpg", "rb") as file:
    image_data = file.read()
    # Perform operations with the binary data

Explanation:

  • We can open a file using the open() function, specifying the file name and the mode in which we want to open it.
  • Writing to a file is done using the write() method, which writes the specified content to the file.
  • Reading from a file is done using the read() method, which reads the entire content of the file.
  • Appending to a file is done using the “a” mode and the write() method, which appends the specified content to the end of the file.
  • Reading a file line by line is done using the readlines() method, which returns a list of lines in the file. We can then iterate over the lines and perform operations.
  • The “with” statement is used to automatically close the file after we’re done working with it. It ensures that the file is properly closed, even if an exception occurs.

Now it’s time for a practical task:

Task 16:

Create a text file called “shopping_list.txt” and write a list of items to it, each on a new line. Then, read the contents of the file and print them. Finally, append a new item to the file and print the updated contents.

Once you’ve completed the task, you can proceed to the next lesson.