Python Day 3: More Stuff with File Handling

Important Message: Please Make sure you have created a seprate folder for each project, and ensure the source file "main.py" present in that specific folder

1. Opening and Reading Files

# Opening a file in read mode
with open("example.txt", "r") as file:
    content = file.read()
    print(content)

# Output: Contents of 'example.txt' are printed

2. Writing to Files

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, this is a new line of text!")

# Output: 'example.txt' now contains the new text

3. Appending to Files

# Appending text to a file
with open("example.txt", "a") as file:
    file.write("\nThis text is appended to the file.")

# Output: Additional text added at the end of 'example.txt'

4. Reading Files Line by Line

# Reading file line by line
with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())  # strip() removes extra whitespace

# Output: Each line of 'example.txt' printed separately

5. Handling Exceptions

# Handling file operations with try-except
try:
    with open("non_existent_file.txt", "r") as file:
        content = file.read()
except FileNotFoundError:
    print("The file does not exist.")

# Output: Prints an error message if file is not found