pythonYou can use theopen()
function to open the file, and use thereadlines()
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 theopen()
function to open the specified file, and specify the mode as'r'
, which means read-only. Then use thereadlines()
method to read multiple lines of the file and return a list containing the contents of all lines. Finally, usefor
to loop through the list and print the contents of each line.
Please note that after reading the file content, you need to use theclose()
method to close the file to release system resources. In addition, if the file to be read does not exist, aFileNotFoundError
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!