Introduction to File HandlingPython provides built-in functions to work with files. The most common operations include:
Opening a file: open()
Reading from a file: read()
, readline()
, readlines()
Writing to a file: write()
, writelines()
Closing a file: close()
Syntax:file = open("filename", "mode")
The
mode
defines how the file will be opened:
'
r
': Read (default mode, raises an error if the file does not exist)
'
w
': Write (creates a new file if it does not exist, overwrites existing content)
'
a
': Append (creates a new file if it does not exist, appends to existing content)
'
x
': Create (creates a new file, raises an error if the file exists)
'
b
': Binary mode (e.g., '
rb
' for reading binary files)
'
t
': Text mode (default mode, used for reading/writing text files)