File handling is an essential aspect of programming, and Python provides built-in functions to perform various operations on files. Here’s a brief tutorial on file handling, covering creating, opening, appending, reading, and writing to files.
1. Creating a File:
# Create a new file (it will be empty if it doesn't exist)
file_path = 'example.txt'
# The 'w' mode stands for write
with open(file_path, 'w') as file:
pass # The 'with' statement automatically closes the file when the block is exited
2. Writing to a File:
file_path = 'example.txt'
# Open the file in write mode ('w')
with open(file_path, 'w') as file:
file.write("Hello, this is a sample text.\n")
file.write("Writing to a file in Python is easy!\n")
3. Appending to a File:
file_path = 'example.txt'
# Open the file in append mode ('a')
with open(file_path, 'a') as file:
file.write("Appending additional text to the file.\n")
4. Reading from a File:
file_path = 'example.txt'
# Open the file in read mode ('r')
with open(file_path, 'r') as file:
content = file.read()
print(content)
5. Reading Line by Line:
file_path = 'example.txt'
# Open the file in read mode ('r')
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
print(line.strip()) # strip() removes newline characters at the end
6. Checking if a File Exists:
import os
file_path = 'example.txt'
if os.path.exists(file_path):
print(f"The file {file_path} exists.")
else:
print(f"The file {file_path} does not exist.")
Remember to replace 'example.txt'
with the actual path and filename you want to work with. File handling in Python is flexible, and you can adapt these examples based on your specific requirements.