How can Python read the contents of a file into a list?

One option:

You can open a file using the open function and use the readlines method to read the contents of the file line by line into a list. Here is an example code:

file_path = "example.txt"  # 文件路径
content_list = []  # 创建一个空列表

with open(file_path, "r") as file:
    for line in file.readlines():
        content_list.append(line.strip())  # 逐行读取并添加到列表中,使用strip方法去除行末的换行符

print(content_list)

This code will store the content of each line in the file in the content_list. It is important to modify the file path according to the actual situation. Additionally, this code uses a context manager (with statement) to ensure that the file is correctly closed after use, to avoid resource leakage.

bannerAds