open()
function to open a file.open(filename, mode)
"r"
: Read mode (default). Opens the file for reading."w"
: Write mode. Opens the file for writing (creates a new file or overwrites an existing file)."a"
: Append mode. Opens the file for appending (writes data to the end of the file)."x"
: Exclusive creation mode. Creates a new file but raises an error if the file already exists."b"
: Binary mode (e.g., "rb"
, "wb"
)."+"
: Read and write mode (e.g., "r+"
, "w+"
).close()
method.with
Statementwith
statement automatically closes the file after the block of code is executed.read()
readline()
readlines()
write()
writelines()
"a"
mode to append data to the end of a file."b"
mode to read or write binary data (e.g., images, videos).seek()
tell()
truncate()
with
statement to ensure files are properly closed.FileNotFoundError
) when working with files.