Python provides built-in functions to read from and write to files.
Opening a File:
file = open('filename.txt', mode)
- Modes:
'r'
: Read (default).'w'
: Write (creates a new file or overwrites).'a'
: Append (adds to the end of the file).'r+'
: Read and write.
Reading from a File:
# Read entire content
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Read line by line
with open('example.txt', 'r') as file:
for line in file:
print(line.strip())
Writing to a File:
# Write to a file
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("This is a new line.")
# Append to a file
with open('output.txt', 'a') as file:
file.write("\nAdding a new line at the end.")
Best Practices:
- Use
with
statement to ensure the file is properly closed after its suite finishes. - Handle exceptions using
try-except
blocks when dealing with file operations.