首页 > 解决方案 > Python - read a text file with multiple lines into a list

问题描述

I would like to turn this (in a .txt file):

7316717653
1330624919

into this (in a Python list):

a_list = [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]

how do I do this? I've been looking everywhere, but nothing came close to what I intended to do

标签: pythonlistreadfile

解决方案


lst = []
with open('New Text Document.txt', 'r') as f: #open the file 
    lines = f.readlines() # combine lines of file in a list
    for item in lines: # iterate through items of  lines
        # iterate through items in each line and remove extra space after last item in the line using strip method
        for digit in item.strip(): 
            lst.append(int(digit)) # append digits in to the list and convert them to int

print(lst)
[7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]

推荐阅读