繁体   English   中英

为什么当我运行代码说“列表”object 没有属性条时,我不断收到错误消息?

[英]why do I keep getting an error message when I run the code saying that 'list' object has no attribute strip?

我编写这段代码是为了读取一个.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'

在我看来,这line是一个列表,无论你是否有意这样做。 strip ()用于字符串,并且没有任何 arguments 传递,它只会从两端删除空格。

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

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

再次查看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...

一旦你遇到这样的错误,重新运行不会让它 go 消失。 这个错误不是随机的!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM