0

I feel like its probably a simple solution but I can’t seem to figure it out and my google-fu is failing me.

currently, I’m consuming data from a CSV file, I then read each line and append to a list. I then use join to combine them all but the output is separated by brackets. What am I missing here?

Code:

data_file = csv.reader(open(‘data.csv’,’r’))
ip_addr=[]

for row in data_file:
    ip_addr.append(row)

combine_ips = ‘,’.join(map(str, ip_addr))

Output

[‘1.1.1.1’],[‘1.1.1.2’],[‘1.1.1.3’]

What I need: ( I need it to be a string of course)

1.1.1.1.1,1.1.1.2,1.1.1.3
4
  • 1
    How about ip_addr.append(row[0])?
    – 0x5453
    Commented Nov 22, 2022 at 21:25
  • row is a list of all the fields in the CSV, so ip_addr() is a list of lists.
    – Barmar
    Commented Nov 22, 2022 at 21:27
  • Is this really a CSV? It seems like it's just a plain text file with one IP in each line. There are no comma separators.
    – Barmar
    Commented Nov 22, 2022 at 21:28
  • of course it does, because the str output of a list uses brackets that way. You want to use formatting Commented Nov 22, 2022 at 21:54

1 Answer 1

1

row evaluates as a list even if it is only a list of 1 in your case, so the first thing you need to do is convert row to a string before appending it to ip_addr. Then, as pointed out by @wrbp you only need to join the (now) string contents of ip_addr:

data_file = csv.reader(open("data.csv","r"))
ip_addr=[]

for row in data_file:
    ip_addr.append("".join(row))

combine_ips = ",".join(ip_addr)
1
  • :facepalm: , this is it! That worked. Thanks for the explanation and thanks @wrbp for the hint.
    – Manik
    Commented Nov 22, 2022 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.