What is the method in Python for reading a file and pri…

Python offers the open() function for reading files and displaying the output. Here is a simple example:

# 打开文件
file = open("example.txt", "r")

# 读取文件内容并输出
content = file.read()
print(content)

# 关闭文件
file.close()

In this example, we are opening a file named “example.txt” using the open() function. The first parameter is the file name, the second parameter is the mode in which to open the file, “r” indicates read mode. Then, we use the read() method to read the file contents and store it in the variable content. Finally, we use the print() function to output the file content. Lastly, we close the file using the close() method.

It should be noted that after opening a file using the open() function, it is necessary to close it with the close() method to release resources. Additionally, you can also use the with statement to automatically manage the opening and closing of the file, as shown below:

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

After opening a file using the with statement, you can directly manipulate the file within the code block of the with statement without manually closing the file.

bannerAds