File handling is an essential part of programming. It allows you to read from and write to files, which is crucial for tasks like data storage, configuration, and logging.
Opening a File
Python provides the open() function to open files. The open() function takes two parameters: the filename and the mode.
Modes
"r": Read mode (default). Opens a file for reading."w": Write mode. Opens a file for writing (creates a new file if it does not exist or truncates the file if it exists)."a": Append mode. Opens a file for appending (creates a new file if it does not exist)."b": Binary mode. Opens a file in binary mode.
Example:
# Open a file named "example.txt" in read mode
file = open("example.txt", "r")Reading a File
To read the contents of a file, you can use methods like read(), readline(), or readlines().
Reading the Entire File:
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()Reading Line by Line:
file = open("example.txt", "r")
for line in file:
print(line)
file.close()Writing to a File
To write to a file, you can use the write() or writelines() methods. Make sure to open the file in write ("w") or append ("a") mode.
Writing a Single Line:
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.close()Writing Multiple Lines:
file = open("example.txt", "w")
lines = ["First line\n", "Second line\n", "Third line\n"]
file.writelines(lines)
file.close()Appending to a File
To append content to an existing file, open the file in append mode ("a").
Example:
file = open("example.txt", "a")
file.write("This line is added to the existing file.\n")
file.close()Closing a File
Always close files after completing operations to free up system resources.
Example:
file = open("example.txt", "r")
# Perform file operations
file.close()Using the with Statement
Using the with statement is a better practice for file handling as it ensures proper resource management.
Example:
with open("example.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed after the with block

