我有麻烦输出所有。csv值到我的。json文件。该脚本仅输出.csv行中的最后一个值。我需要输出的所有值由一个空格分隔,而不使用字典的。csv值。这是我的代码。
#getting variables from csv file
with open(csvfilepath, 'r', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
for row in csvreader:
args_str = row[5][1:]
#select json template
jsonfilename = input("Enter .json template name: ")
jsonfilepath = jsontempdir + jsonfilename
#loading json file
with open(jsonfilepath,'r+', encoding='utf-8') as jsonfile:
data = json.load(jsonfile)
# put args_str in "Args" key
data["Config"]["Script"].update({"Args": args_str})
这里是示例。csv
['#STEP', 'dog', '&NONE', '*0', '^NOP', 'foo', '~1000', '!NONE', '!NONE']
['#STEP', 'cat', '&NONE', '*0', '^NOP', 'bar', '~1000', '!NONE', '!NONE']
['#STEP', '', '&NONE', '*0', '^NOP', 'baz', '~1000', '!NONE', '!NONE']
这是我当前的。json输出
"Config": {
"CustomID": "UPDATED AFTER IMPORT",
"Name": "Execute script function.py",
"Script": {
"Args": "baz",
"ChangeID": "",
"Exists": true,
"Lang": "",
"Name": "",
"Text": ""
这是我想要的输出
"Config": {
"CustomID": "UPDATED AFTER IMPORT",
"Name": "Execute script function.py",
"Script": {
"Args": "foo bar baz",
"ChangeID": "",
"Exists": true,
"Lang": "",
"Name": "",
"Text": ""
当前在每次循环迭代时重写args_str
中的值。相反,您可以尝试连接第5列中的所有值,如下所示:
with open(csvfilepath, 'r', encoding='utf-8') as csvfile:
csvreader = csv.reader(csvfile)
next(csvreader)
args_str = " ".join(row[5] for row in csvreader)