Description: File handling refers to the process of working with files, such as opening, reading, writing, and closing files on your computer or other storage systems.Python provides built-in functions and methods to manage files efficiently.It allows you to manipulate files without needing to open them manually or use external software.
Step-by-Step Process
Opening a File: Files should be opened using the open() function, specifying the file path and mode
Reading from a File: Once a file is open, its contents can be read using methods like read(), readline(), or readlines().
Writing to a File: Files can be written to using methods like write() or writelines(), depends on the type of data you want to write.
Closing a File: After all file operations are complete, its essential to close the file using the close() method to free up system resources.
File modes: 'r' for reading 'w' for writing (overwrites file) a' for appending 'rb', 'wb' for binary read and write operations
Sample Code
#File handling with read and append
file_path = "/home/soft23/Desktop/FileHandling/sample.txt"
with open(file_path, "r") as file:
content = file.read()
print("File Contents before appening:")
print(content)
if "I am living in Chennai." not in content:
with open(file_path, "a") as file:
file.write("I am living in Chennai.\n")
with open(file_path, "r") as file:
updated_content = file.read()
print("\nFile Contents after appending:")
print(updated_content)
#File handling with write
with open(file_path,"w")as file:
file.write("Iam interested in Machine learning.\n")
file.write("So i want to become a machine learning developer in future.\n")
with open(file_path,"r")as file:
write_content=file.read()
print("\nIn write() function it overwrites the contents:")
print(write_content)