luna8899
luna8899

Reputation: 55

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'])

Upvotes: 0

Views: 179

Answers (2)

Alexander Riedel
Alexander Riedel

Reputation: 1359

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])

Upvotes: 2

JUSEOK KO
JUSEOK KO

Reputation: 69

Delete quotation marks in the list eg. ‘sum’ to sum. sum is the name of variable and ‘sum’ is a string object. By adding the quotation marks you are saying that you want to write string ‘sum’ and ‘diff’.

Upvotes: 0

Related Questions