Home > Back-end >  How to output all .csv values without using a dictionary?
How to output all .csv values without using a dictionary?

Time:05-18

I'm having trouble outputting all .csv values into my .json file. The script only outputs the last value in the .csv row. I need all values to be outputted separated by a space without using a dictionary for the .csv values. Here is my code.

    #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})

here is the example .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']

here is my current .json output

    "Config": {
        "CustomID": "UPDATED AFTER IMPORT",
        "Name": "Execute script function.py",
        "Script": {
            "Args": "baz",
            "ChangeID": "",
            "Exists": true,
            "Lang": "",
            "Name": "",
            "Text": ""

here is my desired output

    "Config": {
        "CustomID": "UPDATED AFTER IMPORT",
        "Name": "Execute script function.py",
        "Script": {
            "Args": "foo bar baz",
            "ChangeID": "",
            "Exists": true,
            "Lang": "",
            "Name": "",
            "Text": ""

CodePudding user response:

You are currently overwriting the value in args_str at every iteration of the loop. Instead, you could try to concat all the values in the 5th column like so:

with open(csvfilepath, 'r', encoding='utf-8') as csvfile:
    csvreader = csv.reader(csvfile)
    next(csvreader)
    args_str = " ".join(row[5] for row in csvreader)
  • Related