G. Hally
G. Hally

Reputation: 25

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

Upvotes: 1

Views: 4321

Answers (3)

Khalil Al Hooti
Khalil Al Hooti

Reputation: 4546

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]

Upvotes: 4

Abdul Rehman
Abdul Rehman

Reputation: 5684

Here's a complete solution:

num = '''7316717653
      1330624919'''
num = num.replace('\n', '')
# Write to a text file:
with open('filename.txt', 'w') as f:
    f.write(num)

# Now write to a Python List:
fd = open('filename.txt','rU')
chars = []
for line in fd:
    chars.extend(line)

Output is: [7, 3, 1, 6, 7, 1, 7, 6, 5, 3, 1, 3, 3, 0, 6, 2, 4, 9, 1, 9]

Upvotes: 0

Bharath
Bharath

Reputation: 174

with open('txtfile', 'r') as f:
    x = f.read()
print [y for y in list(x) if y != '\n']

Upvotes: 0

Related Questions