Junior — Middle
How is file access for reading and writing implemented in Python?
sobes.tech AI
Answer from AI
In Python, access to files for reading and writing is done using the built-in open() function. It opens a file and returns a file object that can be worked with.
Main file opening modes:
'r'— read (the file must exist)'w'— write (the file is created or truncated)'a'— append to the end of the file'b'— binary mode (added to other modes, e.g.,'rb')
Example of reading a file:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
Example of writing to a file:
with open('example.txt', 'w', encoding='utf-8') as file:
file.write('Example of writing to a file\n')
Using the with statement guarantees that the file will be closed automatically after exiting the block, even if an error occurs.
For more complex operations, you can use methods of the file object such as readline(), readlines(), write(), writelines(), etc.