To open a file in Python, you use the built-in open()
function. This function takes two main parameters: the file path and the mode in which you want to open the file.
file = open('example.txt', 'r')
'r'
: Read mode (default). Opens a file for reading.'w'
: Write mode. Opens a file for writing (and truncates the file to zero length).'a'
: Append mode. Opens a file for writing, appending to the end of the file if it exists.'b'
: Binary mode. Can be combined with other modes (e.g., 'rb'
or 'wb'
for reading or writing in binary).'+'
: Update mode. Can be combined with other modes (e.g., 'r+'
, 'w+'
, or 'a+'
for reading and writing).