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

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

我在这里做了一些研究,但无法完全找到我正在寻找的确切答案。所以我想我会寻求一些支持。我一直在研究 python 脚本,该脚本将搜索 CSV 并检查最后一列是否为 'TRUE',如果是,则检索 ID 和主机名。下面我贴出了代码和错误。任何帮助将不胜感激!我确定这是一个简单的问题...

可能不应该是我的目标。我试图让这部分用这个“命令”列出每个主机名。有没有办法做到这一点?

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

这是 CSV:

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

这是脚本示例:

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)

我收到错误:

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

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 = [] 放在 for 循环之前和 if 块内 do

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

就像您对 HOSTNAME_HOST 所做的那样。

或者,您可以使用 list comprehension:

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

您甚至可以将整个 for 循环替换为:

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