Definition of File Handling:
File handling refers to the process of creating, opening, reading, writing, appending, and closing files in a program. It allows managing files to store and retrieve data efficiently. File handling is essential for tasks like saving user data, processing logs, and generating reports.
In Python, file handling is performed using built-in functions such as:
open()
: Opens a file in the specified mode (e.g., read, write, append).read()
andreadline()
: Read data from a file.write()
: Write data to a file.close()
: Closes the file to free up resources.
File modes include:
"r"
: Read mode (default)."w"
: Write mode (overwrites existing content)."a"
: Append mode (adds new content to the end)."r+"
: Read and write mode.
Reading from a file:
Program:
# Reading from a file
f = open("fruits.txt", "r") # Opens the file in read mode
content = f.read() # Reads the entire content of the file
print("Initial content of the file:")
print(content) # Prints the content
f.close() # Closes the file
0 Comments