pythonYou can use the open()
function to open the file, and use the readlines()
method to read multiple lines of the file.
Here is an example:
# 打开文件 file = open('文件路径', 'r') # 读取文件的多行内容 lines = file.readlines() # 关闭文件 file.close() # 打印每一行内容 for line in lines: print(line)
In this example, first use the open()
function to open the specified file, and specify the mode as 'r'
, which means read-only. Then use the readlines()
method to read multiple lines of the file and return a list containing the contents of all lines. Finally, use for
to loop through the list and print the contents of each line.
Please note that after reading the file content, you need to use the close()
method to close the file to release system resources. In addition, if the file to be read does not exist, a FileNotFoundError
exception will be thrown, so error handling is required in actual use.
The above is the detailed content of How to read multi-line content of a file in python. For more information, please follow other related articles on the PHP Chinese website!