0

I want to read from the pList.csv file and write all item in a string, such that each row is separated by a comma.

the file has only one column. for example, the pList.csv is :

28469977

24446384

25968054

and output string must be: 28469977,24446384,25968054

for do this, have considered the following code. but there is a little problem

p_list = ""
with open("pList.csv", mode="r") as infile:
    reader = csv.reader(infile)
    for row in reader:
        p_list += row[0]
        if its_not_last_loop :
            p_list += ","

What expression is appropriate for its_not_last_loop so that , is not applied to the last row of the file?

Saam
  • 75
  • 8

2 Answers2

0

Try this:

with open("pList.csv", mode="r") as infile:
    reader = csv.reader(infile)
    out_list = []
    for row in reader:
        out_list.append(row[0]) #row[0] get value for the sample input
    p_list = ",".join(out_list)
    print(p_list)

See What exactly does the .join() method do?

Saam
  • 75
  • 8
Kaushal Kumar
  • 1,237
  • 1
  • 12
  • 21
0

This can be shortened to (and is faster)

with open("pList.csv", mode="r") as infile:
    reader = csv.reader(infile)
    p_list = ",".join(row[0] for row in reader)
    print(p_list)
rioV8
  • 24,506
  • 3
  • 32
  • 49