Skip to content

Latest commit

 

History

History
171 lines (122 loc) · 4.44 KB

README.md

File metadata and controls

171 lines (122 loc) · 4.44 KB

Chapter 12: File Handling

Table of Contents

Reading and Writing Text Files

In Python, you can read and write text files using the built-in open() function. The open() function takes two arguments: the file name and the mode in which the file should be opened.

Reading Text Files

You can read the contents of a text file using the read(), readline(), or readlines() methods.

# Reading the entire file
with open("file.txt", "r") as f:
    content = f.read()
    print(content)

# Reading the file line by line
with open("file.txt", "r") as f:
    for line in f:
        print(line.strip())

Output:

1) The wind howls through the empty streets, carrying whispers of forgotten tales.
2) A flickering streetlight casts long shadows on the ground, adding to the mystery.
3) In the distance, a train’s whistle echoes, announcing its arrival in the quiet town.
4) The smell of fresh bread wafts through the air from a bakery nearby.
5) Leaves rustle underfoot as people walk, their footsteps blending with the natural sounds.

Writing Text Files

You can write to a text file using the write() method. If the file does not exist, it will be created.

# Writing to a file
with open("langs.txt", "w") as f:
    f.write("Python\nKotlin\nC++\nTypeScript\nC#")

# Appending to a file
with open("langs.txt", "a") as f:
    f.write("\nJavaScript")

Output in langs.txt:

Python
Kotlin
C++
TypeScript
C#
JavaScript

Working with Binary Files

Binary files store data in binary format. You can read and write binary files using the rb and wb modes.

Reading Binary Files

with open("image.jpg", "rb") as f:
    content = f.read()
    print(content[:20])  # Print the first 20 bytes

Writing Binary Files

with open("copy.jpg", "wb") as f:
    f.write(content)

Using Context Managers (with statement)

The with statement is used to wrap the execution of a block of code. It ensures that resources are properly managed, such as closing a file after it has been opened.

Example: Using Context Managers

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

Explanation: The with statement ensures that the file is properly closed after it has been read.

File Methods and Operations

Python provides several methods and operations for working with files.

Checking if a File Exists

import os

if os.path.exists("file.txt"):
    print("The file exists.")
else:
    print("The file does not exist.")

Deleting a File

if os.path.exists("test.txt"):
    os.remove("test.txt")
else:
    print("There is no such file to delete.")

Renaming a File

os.rename("old_name.txt", "new_name.txt")

Getting File Information

file_info = os.stat("file.txt")
print(f"File size: {file_info.st_size} bytes")
print(f"Last modified: {file_info.st_mtime}")

Handling File Exceptions

When working with files, you may encounter exceptions. It is important to handle these exceptions to prevent your program from crashing.

Example: Handling File Exceptions

try:
    with open("non_existent_file.txt", "r") as f:
        content = f.read()
except FileNotFoundError:
    print("The file does not exist.")
except IOError:
    print("An I/O error occurred.")

Explanation: The try-except block is used to handle exceptions that may occur when working with files.

Summary

In this chapter, we covered file handling in Python, including reading and writing text files, working with binary files, using context managers, file methods and operations, and handling file exceptions.

Tasks

  1. Write a program that reads a text file and prints its contents to the screen.
  2. Write a program that writes a list of strings to a text file.
  3. Write a program that reads a binary file and prints the first 20 bytes.
  4. Write a program that checks if a file exists and deletes it if it does.
  5. Write a program that handles exceptions when trying to read a non-existent file.

Next Chapter: Conclusion and Further Learning