How to get list form txt file (Python)

Viewed 76

everyone!

I have a simple txt file, with few number in a row (',' is separator)

"1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21"

and this code:

num=[]
f = open('sample.txt','r')

for i in f:
    num.append(i.split(',')
print(num)

my goal is to get list of items:

['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']

but i get list i list with 1 item:

[['1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21']]

looking for help

3 Answers

If you only have one line in your file, you don't need to loop over lines. You can assign num directly:

with open('sample.txt','r') as f:
    num = f.read().split(',')
This code will work even if you have multiple line to read


num=[]
f=open('input.txt')

for i in f:
    for j in (i.split(',')):
        num.append(j.replace('\n',''))
        
print(num)        
    

Explanation line by line steps

1.creating empty list

2.opening file

3.Taking one element from f at a time

4.splitting i which returns list and than taking one item from list as j

5.appending j and if there is newline character in j, than remove \n (this happens when we have to read more than on line)

Related