File Handling in python

File Handling Examples

Writing to a File


file_content = "Hello, this is some content to write to the file."
with open("example_file.txt", "w") as file:
    file.write(file_content)
print("Content written to the file.")


Content written to the file.

Reading from a File


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


File content:
Hello, this is some content to write to the file.

Appending to a File


additional_content = "\nAppending this to the file."
with open("example_file.txt", "a") as file:
    file.write(additional_content)
print("Content appended to the file.")


Content appended to the file.

Reading Line by Line


with open("example_file.txt", "r") as file:
    lines = file.readlines()
print("Lines in the file:")
for line in lines:
    print(line.strip())  # Strip newline characters


Lines in the file:
Hello, this is some content to write to the file.
Appending this to the file.

Checking if a File Exists


import os
file_name = "example_file.txt"
if os.path.exists(file_name):
    print(f"The file '{file_name}' exists.")
else:
    print(f"The file '{file_name}' does not exist.")


The file 'example_file.txt' exists.



Click this for OOPs in Python

Click this for Exception Handling

Click this for File Handling


Comments