File Handling in Python
File handling in Python is a crucial aspect of programming that
allows you to read, write, and manipulate files. Python provides
built-in functions and methods to handle file operations
efficiently.
Opening and Closing Files
The built-in open() function is used to open a file. It takes the file
path and mode as arguments. Common modes are:
'r' : Read (default mode)
'w' : Write (creates a new file if it doesn't exist or truncates
the file if it exists)
'a' : Append (creates a new file if it doesn't exist)
'b' : Binary mode (used with other modes like 'rb', 'wb')
'+' : Read and Write (used with other modes like 'r+', 'w+',
'a+')
Example:
# Open a file in read mode
file = open("example.txt", "r")
# Close the file
file.close()
Using with Statement
Using the with statement is a better practice because it ensures
the file is properly closed after its suite finishes, even if an
exception is raised.
Example:
# Using with statement to open a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
Reading Files
read(): Reads the entire content of the file.
readline(): Reads one line from the file.
readlines(): Reads all the lines and returns them as a list.
Example:
with open("example.txt", "r") as file:
content = file.read() # Read the entire content
file.seek(0) # Move the cursor to the beginning
first_line = file.readline() # Read the first line
file.seek(0) # Move the cursor to the beginning
all_lines = file.readlines() # Read all lines as a list
print("Entire content:", content)
print("First line:", first_line)
print("All lines:", all_lines)
Writing Files
write(): Writes a string to the file.
writelines(): Writes a list of strings to the file.
Example:
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.writelines(["This is the first line.\n", "This is the second
line.\n"])
Appending to Files
a mode: Opens the file for appending.
Example:
with open("example.txt", "a") as file:
file.write("This is an appended line.\n")