我無法將所有 .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": ""
uj5u.com熱心網友回復:
您當前正在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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476502.html
