Sobes.tech
Junior — Middle

How can a file be opened in a program?

sobes.tech AI

Answer from AI

In Python, the built-in function open() is used to open a file. It returns a file object that can be worked with — read, write, etc.

Example of opening a file for reading:

with open('example.txt', 'r', encoding='utf-8') as file:
    content = file.read()
    print(content)

Here, with ensures that the file will be automatically closed after exiting the block. The 'r' parameter indicates read mode. For writing, use 'w', and for appending, 'a'.

This approach is convenient and safe, as it prevents resource leaks.