如何在不使用字典的情况下输出所有 .csv 值?
How to output all .csv values without using a dictionary?
我在将所有 .csv 值输出到我的 .json 文件时遇到问题。该脚本仅输出 .csv 行中的最后一个值。我需要输出所有值并用 space 分隔,而不使用 .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)
我在将所有 .csv 值输出到我的 .json 文件时遇到问题。该脚本仅输出 .csv 行中的最后一个值。我需要输出所有值并用 space 分隔,而不使用 .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)