2 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
簡(jiǎn)短的回答
csv.reader 讀入字符串。您可以通過使用一些類型轉(zhuǎn)換來(lái)解決這個(gè)問題:
import csv
file = open("reads.csv", "r")
reader = csv.reader(file)
for line in reader:
value0 = line[0]
value1 = line[1]
value2 = int(line[0]) + int(line[1])
t = value0,value1,value2
print(t)
以上,我假設(shè)您的數(shù)據(jù)是整數(shù)格式。如果數(shù)據(jù)是浮點(diǎn)格式,你會(huì)想使用 float() 代替。
建議改進(jìn)
一般來(lái)說(shuō),我建議使用以下內(nèi)容:
import csv
with open("reads.csv", "r") as file:
reader = csv.reader(file)
column_numbers = [0,1]
for line in reader:
t = sum(int(line[i]) for i in column_numbers)
print(t)
這將在代碼塊執(zhí)行后自動(dòng)關(guān)閉文件,避免以后出錯(cuò)。列號(hào)也以數(shù)組的形式給出,以便您以后可以輕松地將它們換掉。

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
嘗試以下將讀取中的字符串轉(zhuǎn)換為整數(shù)的方法:
import csv
f = open("inputdata.csv", "a")
f.write("1,2,3,4,5")
f.write("6,7,8,9,10")
f.write("11,12,13,14,15")
f.close()
file=open( "inputdata.csv", "r")
reader = csv.reader(file)
for line in reader:
value0=int(line[0])
value1=int(line[1])
value2=int(line[0])+int(line[1])
t=value0,value1,value2
print(t)
輸出:
(1, 2, 3)
(6, 7, 13)
(11, 12, 23)
添加回答
舉報(bào)