Search code examples
pythoncsvexport-to-csv

How can I import the values of a variable in a csv file, in python?


I need to import the values of the variables sum and diff into my test.csv file, how can I do that? I leave my code below:

x=3
y=5
z=2
sum=x + y + 5
diff= x-y-5

with open('test.csv', 'w', newline='') as f:
    thewriter.writerow(['sum', 'diff'])

Solution

  • Don't use sum as a variable name in Python as it is the name for a builtin function. Also quotes define a string and don't refer to a variable.

    dif = 10
    print('dif')
    print(dif)
    

    outputs:

    dif
    10
    

    your code would look like

    import csv
    
    x=3
    y=5
    z=2
    sum_x_y=x + y + 5
    diff= x-y-5
    
    with open('test.csv', 'w', newline='') as f:
        thewriter = csv.writer(f)
        thewriter.writerow(["sum_x_y", "diff"])
        thewriter.writerow([sum_x_y, diff])