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
# 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
# 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
# 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'
# 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
# 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
« Previous
Next »