如何在 python 中导入 csv 文件中的变量值?

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

我需要将变量 sum 和 diff 的值导入我的 test.csv 文件,我该怎么做?我在下面留下我的代码:

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

不要在 Python 中使用 sum 作为变量名,因为它是内置函数的名称。引号也定义了一个字符串,而不是引用一个变量。

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

输出:

dif
10

你的代码看起来像

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

删除列表中的引号,例如。 ‘求和’求和。 sum 是变量的名称,“sum”是一个字符串对象。 通过添加引号,您表示您想要编写字符串“sum”和“diff”。