'r'
- Read Mode:
IOError
is raised.'w'
- Write Mode:
'a'
- Append Mode:
'x'
- Exclusive Creation Mode:
IOError
is raised.Text Mode:
't'
: This is the default mode. It handles the file as text.Binary Mode:
'b'
: Handles the file as binary.Read and Write Mode:
'r+'
: Opens the file for both reading and writing.IOError
if the file does not exist.Write and Read Mode:
'w+'
: Opens the file for both writing and reading.Append and Read Mode:
'a+'
: Opens the file for both appending and reading.Binary Read and Write:
'rb'
: Opens the file as binary for reading.'wb'
: Opens the file as binary for writing.'ab'
: Opens the file as binary for appending.'r+b'
or 'rb+'
: Opens the file as binary for reading and writing.'w+b'
or 'wb+'
: Opens the file as binary for writing and reading.'a+b'
or 'ab+'
: Opens the file as binary for appending and reading.Newline Characters:
\n
) are automatically converted to the system default.File Pointer:
'a'
and 'a+'
place the file pointer at the end, so writes append data.Error Handling:
'r'
or 'r+'
mode raises an IOError
.'x'
mode raises an IOError
.Reading a File:
with open('example.txt', 'r') as file:
content = file.read()
print(content)
Writing to a File:
with open('example.txt', 'w') as file:
file.write('Hello, World!')
Appending to a File:
with open('example.txt', 'a') as file:
file.write('\nAppending this line.')
Binary File Operations:
with open('example.bin', 'wb') as file:
file.write(b'\x00\x01\x02')