Read/Write Files
Reading from a File:
Reading the Entire Content:
# Using with statement to automatically close the file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Line by Line:
# Using with statement to automatically close the file
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes leading and trailing whitespaces
Writing to a File:
Writing a String:
# Using with statement to automatically close the file
with open("output.txt", "w") as file:
file.write("Hello, World!\\n")
file.write("Python is great!")
Writing Multiple Lines:
lines = ["Line 1", "Line 2", "Line 3"]
# Using with statement to automatically close the file
with open("output.txt", "w") as file:
file.writelines("\\n".join(lines))
Appending to a File:
# Using with statement to automatically close the file
with open("output.txt", "a") as file:
file.write("\\nAppending a new line.")
Binary Mode:
# Using with statement to automatically close the file
with open("binary_data.bin", "wb") as file:
data = b'\\x48\\x65\\x6c\\x6c\\x6f' # Binary data (Hello in ASCII)
file.write(data)
Reading and Writing Files Line by Line:
# Reading from one file and writing to another line by line
with open("input.txt", "r") as input_file, open("output.txt", "w") as output_file:
for line in input_file:
output_file.write(line)
Always remember to close the file after reading from or writing to it. The with
statement is recommended as it automatically closes the file, even if an exception occurs during the operation.
These examples should give you a good starting point for reading and writing files in Python. Adjust the file paths and content based on your specific requirements.