首页 > 解决方案 > 使用python添加csv文件的列

问题描述

我在添加 Excel 工作表的两列中存在的数据并获取其结果时遇到了问题。我尝试了下面的代码,但它连接了下面的列。请帮忙

file=open( "reads.csv", "r")
    reader = csv.reader(file)
    for line in reader:
        value0=line[0]
        value1=line[1]
        value2= line[0]+line[1]       
        t=value0,value1,value2

        print(t)

('50437171', '150', '50437171150')
('50463638', '107', '50463638107')
('101891833', '150', '101891833150')
('101891682', '151', '101891682151')
('148515110', '150', '148515110150')
('139044904', '119', '139044904119')
('139056020', '151', '139056020151')
('151860851', '103', '151860851103')
('139044904', '151', '139044904151')
('139044905', '150', '139044905150')
('50444197', '151', '50444197151')

标签: pythoncsv

解决方案


简短的回答

csv.reader 读入字符串。您可以通过使用一些类型转换来解决这个问题:

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)

以上,我假设您的数据是整数格式。如果数据是浮点格式,你会想使用 float() 代替。

建议改进

一般来说,我建议使用以下内容:

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)

这将在代码块执行后自动关闭文件,避免以后出错。列号也以数组的形式给出,以便您以后可以轻松地将它们换掉。

享受!


推荐阅读