Search code examples
pythonlisterror-handlingexport-to-csv

list to csv file - AttributeError: 'str' object has no attribute 'writer'


I would like to convert the following list

csv_list[:5]
[['s01_l01/1_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_1.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_2.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_3.png', '1', '7C2 4698', '7C24698'],
 ['s01_l01/2_4.png', '1', '7C2 4698', '7C24698']]

to a csv file.

I used this code:

with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(csv_list)

And got this error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-65-30765791e5c8> in <module>()
      1 with open('/content/gdrive/My Drive/data/2017-IWT4S-CarsReId_LP-dataset/TrainValV1.csv', 'w', newline='') as file:
----> 2     writer = csv.writer(file)
      3     writer.writerows(csv_list)

AttributeError: 'str' object has no attribute 'writer'

What do I have to change?

Thanks a lot!


Solution

  • This must mean that csv in line two in that error output is an object of type str, as the error message says. If you post the full code, which shows how you define csv, we could narrow down why that is. Likely you define something else, like csv = '<some string>' sometime after you import csv.

    I'll expand a bit about when you usually see AttributeErrors in Python, so that you might be able to spot this type of thing quicker in the future. You see that error when you have a line like:

    # will error if x does not actually have this attribute
    x.some_attribute_y
    # This line is basically equivalent to the above line:
    getattr(x, 'some_attribute_y')
    

    The error message will say:

    AttributeError: '<type of object x>' object has no attribute 'some_attribute_y'