Search code examples
pythonpython-itertools

csv.reader prints ['var'] instead of var


When I read a csv and sub the row value into a string variable is prints '['var']' but I need just var.

from itertools import islice
import csv


with open("test12.csv") as tl:
    for row in islice(csv.reader(tl), 0, None):
        rowlink = f"https://www.footballdb{row}/roster"
        print(rowlink)

this code prints

https://www.footballdb['test1']/roster
https://www.footballdb['test2']/roster
[Finished in 0.047s]

I need to remove the square brackets and quotations

thank you in advance


Solution

  • I'm assuming that your csv file looks something like

    test1
    test2
    

    And you're expecting a plain list like ['test1', 'test2'].

    The problem is that csv.reader should be returning a nested list, so it's more like [['test1'], ['test2']].

    You should be able to get the desired output as a string rather than a list, which you are currently printing, by selecting the first item in the list as follows:

    from itertools import islice
    import csv
    
    
    with open("test12.csv") as tl:
        for row in islice(csv.reader(tl), 0, None):
            rowlink = f"https://www.footballdb{row[0]}/roster"
            print(rowlink)