Search code examples
pythoncsvtypeerror

Python: TypeError: can only concatenate str (not "list") to str


I have done some research on here and can't quite find the exact answer I'm looking for. So I figured I would reach out for some support. I have been working on a python script that will search a CSV and check if the last column is 'TRUE', if it is then it retrieves the id and hostname. Below I have posted the code and the error. Any help would be greatly appreciated! I'm sure it's a simple issue...

Probably should not my goal. I am trying to get this portion to list out each hostname with this "command". Is there even a way to do this or no?

COMMANDS = ("get 'C:\\" + HOSTNAME_HOST + ".zip'")

Here is the CSV:

hostname,id,enabled
WIN10_PC,asdfasdfasdfasdfasdfasdf,TRUE
WIN_Server,asdfasdfasdfasdfasdfasdf,TRUE

Here is a sample of the script:

import csv

AIDS_TO_EXECUTE = []
HOSTNAME_HOST = []
with open('hosts_to_execute.csv', 'rt') as csvfile:
    data = csv.reader(csvfile, delimiter=',')
    for hostname, aid, enabled in data:
        if enabled == 'TRUE':
            AIDS_TO_EXECUTE.append(aid)
            HOSTNAME = (hostname)
            HOSTNAME_HOST.append(HOSTNAME)
            
COMMANDS = ("get 'C:\\" + HOSTNAME_HOST + ".zip'")

#print(COMMANDS)

print(HOSTNAME_HOST)

Error I am recieving:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    COMMANDS = ("get 'C:\\" + HOSTNAME_HOST + ".zip'")
TypeError: can only concatenate str (not "list") to str

Solution

  • I am trying to get this portion to list out each hostname with this "command". Is there even a way to do this or no?

    The simplest way is to put COMMANDS = [] before the for loop and within the if block do

                COMMANDS.append("get 'C:\\" + HOSTNAME + ".zip'")
    

    just like you did with HOSTNAME_HOST.

    Alternatively, you could use a list comprehension:

    COMMANDS = ["get 'C:\\" + h + ".zip'" for h in HOSTNAME_HOST]
    

    You could even replace the whole for loop with:

        AIDS_TO_EXECUTE, HOSTNAME_HOST, COMMANDS = \
            zip(*[(a, h, "get 'C:\\" + h + ".zip'") for h, a, e in data if e == 'TRUE'])