为什么我在运行代码时说“列表”对象没有属性栏,为什么仍然收到错误消息?

时间:2019-10-29 02:13:18

标签: python

我编写了这段代码以读取.csv文件,然后编写一个新的.csv文件,所有文件都完全相同,除了它有第六行,第四和第五列中的整数加在一起。这是我写的

import csv
def computed_column (x) :
    with open(x, 'r') as f:
        reader = csv.reader(f)
        with open('introduce.csv', 'w') as g :
            writer = csv.writer(g)
            for line in reader:
                line = line.strip().split(',')
                sum1 = str(int(line[3]+line[4]))
                writer.writerow(line + ',' + sum1 + '\n' )

每次我尝试运行它时,我都会收到一条错误消息,说'list' object has no attribute 'strip'

2 个答案:

答案 0 :(得分:0)

在我看来strip ()是一个列表,无论您是否故意这样做。 color: red !important; 用于字符串,如果不传递任何参数,它将从两端移去空白。

https://www.programiz.com/python-programming/methods/string/strip

https://realpython.com/python-csv/

答案 1 :(得分:0)

再次查看csv.reader的文档:

csv.reader(csvfile, dialect='excel', **fmtparams)
    Each row read from the csv file is returned as a list of strings. 

https://docs.python.org/3/library/csv.html

您的代码:

        for line in reader:
            line = line.strip().split(',')

假定line是一个字符串,例如读取纯文件时得到的字符串。但是您正在使用csv.reader,它已经进行了剥离和分割。

您可以跳过reader而只是

 for line in f:
     line = line.split().strip...

一旦遇到这样的错误,重新运行就不会消失。此错误不是随机的!