Always close files after using them to free system resources.
File handling allows Python programs to create, read, write and manage files. It is used to store data permanently.
The open() function is used to open a file.
file = open("data.txt","r")
print(file.read())
file.close()
file = open("student.txt","r")
content = file.read()
print(content)
file.close()
file = open("notes.txt","w")
file.write("Python File Handling")
file.close()
Append mode adds new content without deleting old data.
file = open("notes.txt","a")
file.write("\nLearning Python")
file.close()
The close() method closes the opened file.
file.close()
The with statement automatically closes the file.
with open("data.txt","r") as file:
print(file.read())
with open("message.txt","w") as file:
file.write("Hello Python")
File handling is used to save and manage data permanently.
The open() function is used to open files.
close() is used to close an opened file.