Sobes.tech
Junior — Middle

How can you open and read the contents of a file if only its name is known?

sobes.tech AI

Answer from AI

To open a file and read its contents knowing only the filename, Python uses the open() function. Usually, the file is opened in read mode ('r'), and then the contents are read using the read() method.

Example:

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

Here, with ensures the file is closed after reading. The read() method reads the entire text from the file into the string content.