2

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

Dmitry
  • 23
  • 5

3 Answers3

1

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(',')
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • Nice, it's work! But can u explain about '*'? – Dmitry Mar 05 '21 at 18:19
  • 1
    The '*' was a parameter unpacking to turn the map(int,... back into a list. I removed it when I realized your expected output was a list of strings (I initially thought you needed integers). – Alain T. Mar 05 '21 at 18:21
1
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)

0

Use extend, instead of append. What is the difference between Python's list methods append and extend?

  num=[]
    f = open('sample.txt','r')
    
    for i in f:
        num.extend(i.split(','))
    print(num)
Rima
  • 1,447
  • 1
  • 6
  • 12