Python provides robust file handling capabilities, allowing you to create, read, update, and delete files. Here’s a breakdown of the essential file handling operations:
Opening a File
Python uses the open()
function to open files, which returns a file object.
Syntax:
file = open("filename", "mode")
Common file modes include:
"r"
– Read (default): Opens the file for reading; error if the file does not exist.
"w"
– Write: Opens the file for writing, creates a new file if it doesn’t exist, or truncates the file if it exists.
"a"
– Append: Opens the file for appending; creates the file if it doesn’t exist.
"r+"
– Read and Write: Opens the file for both reading and writing.