Python Read File: Complete Guide
To output the contents of a file, you can use the built-in function open() in Python to open the file, then use the read() or readlines() method to read the contents of the file, and finally print it out or perform other operations. Here is a simple example code:
# 打开文件
with open("file.txt", "r") as file:
# 读取文件内容
content = file.read()
# 打印文件内容
print(content)
In the code above, the open() function is used to open a file named “file.txt” in read mode (“r”). The read() method is then used to read the file content and assign it to the variable content, which is then printed using the print() function.
If you want to output the file content line by line, you can do so by using the readlines() method.
# 打开文件
with open("file.txt", "r") as file:
# 读取文件内容
lines = file.readlines()
# 逐行打印文件内容
for line in lines:
print(line)
The code above is similar to the previous one, except that it uses the readlines() method to read the file content line by line and uses a for loop to print each line.