Skip to content Skip to sidebar Skip to footer

Compare Values With Fieldnames Before Writing It In Csv File Using Python

I'm using this code to compare value with their affiliated fieldnames before i store it in the csv-file to check the right column, because everytime when i reboot my machine the or

Solution 1:

for sensor, value  in data.items():
    if sensor in data.items()==sensor in fieldnames:
        v = data[sensor]
        print("v", v)
        lineValue+= str(v) + "," 

This doesn't look right to me. If you just want to iterate through all the fieldnames (other than "Time") and add the values in data that correspond to those fields, while also putting "n/a" for values not present in data, then I suggest doing:

with open(filename,'a') as outfile:
    lineValue = ""
    for fieldname in fieldnames[1:]: #skip the first one, since that's Time, which we have a custom value for already.
        v = data.get(fieldname, "n/a")
        lineValue += str(v) + ","
    lineValue = Time + "," + lineValue[:-1] + "\n"
    print(lineValue)
    outfile.write(lineValue)
    outfile.close()

Bonus suggestion: Adding commas between values manually is an error-prone approach. If possible, use DictWriter, which takes care of most formatting problems for you.

with open(filename,'a') as outfile:
    writer = csv.DictWriter(outfile, fieldnames)
    row = {}    
    for fieldname in fieldnames: #no need to skip Time here, we'll just overwrite it later.
        row[fieldname] = data.get(fieldname, "n/a")
    row["Time "] = Time
    writer.writerow(row)

If you insist on not doing that, at least store the values in a list, which you join once at the end:

with open(filename,'a') as outfile:
    values = [Time]
    for fieldname in fieldnames[1:]:
        v = data.get(fieldname, "n/a")
        values.append(str(v))
    outfile.write(",".join(values) + "\n")

Bonus bonus suggestion: if these solutions add extra empty lines between rows that you don't want, you open the file with the newline="" argument (if using Python 3):

with open(filename,'a', newline="") as outfile:

... Or open the file in binary mode (if using Python 2):

with open(filename,'ab') as outfile:

Post a Comment for "Compare Values With Fieldnames Before Writing It In Csv File Using Python"