AttributeError: 'list' object has no attribute 'strip'

后端 未结 2 1107
日久生厌
日久生厌 2020-12-22 07:31

The following code is causing AttributeError: \'list\' object has no attribute \'strip\' and I do not how to fix it:

#!/usr/bin/env python
from __future__ im         


        
相关标签:
2条回答
  • 2020-12-22 07:47

    You have split your lines into columns:

    parts = (line.split(',') for line in f)
    

    then try to strip each list of columns:

    column = (part.strip() for part in parts)
    

    That won't work. Strip each column instead:

    column = ([col.strip() for col in part] for part in parts)
    

    You may want to use the csv module to do the transformation from file to row-of-data instead however:

    with open("/home/mic/tmp/test.txt", 'rb') as f:
        reader = csv.reader(f, skipinitialspace=True)
        for object_ in iter_something(reader):
            print(object_)
    

    The skipinitialspace option makes sure that a space directly following the delimiter is removed. A newline at the end of each line removed as a matter of course.

    0 讨论(0)
  • 2020-12-22 08:01

    parts = (line.split(',') for line in f) strip when you split as you are creating lists with split:

    parts = (line.strip().split(',') for line in f)
    
    0 讨论(0)
提交回复
热议问题