Use the built-in open() function to open a file. It's crucial to close files when done to free up resources.
# Opening a file
file_object = open("filename.txt", "mode")
# Closing a file
file_object.close()
"filename.txt": The path to the file."mode": A string indicating how the file should be opened (see File Modes below).file_object: A variable representing the opened file.Specify how the file will be used.
'r': Read mode (default). Opens for reading. Error if file doesn't exist.'w': Write mode. Opens for writing. Creates the file if it doesn't exist, truncates (clears) the file if it does.'a': Append mode. Opens for writing. Creates the file if it doesn't exist, appends to the end of the file if it does.'x': Exclusive creation mode. Opens for writing. Creates the file, but raises an error if it already exists.'b': Binary mode. Used for non-text files (e.g., images, executables). Combine with other modes (e.g., 'rb', 'wb).'t': Text mode (default). Used for text files. Combine with other modes (e.g., 'rt', 'wt).'+': Open a file for updating (reading and writing). Combine with other modes (e.g., 'r+', 'w+', 'a+', 'x+').Methods to read content from an opened file object.