Sobes.tech
Junior — Middle

What methods can be used to open a file in Python for reading or writing?

sobes.tech AI

Answer from AI

In Python, the open() function is used to open files. Main ways to open files for reading and writing:

  • Reading:

    • open('filename', 'r') — open a file for reading (default mode).
    • open('filename', 'rb') — open a file for reading in binary mode.
  • Writing:

    • open('filename', 'w') — open a file for writing; if the file exists, it will be overwritten.
    • open('filename', 'a') — open a file for appending data at the end.
    • open('filename', 'wb') — open a file for writing in binary mode.

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')

Using the with statement guarantees automatic closing of the file after the work is done.