Home > Net >  I am just learning and I am asked to write a csv file I keep getting an error but I don't know
I am just learning and I am asked to write a csv file I keep getting an error but I don't know

Time:10-27

import csv

with open('myaddresses.csv','w','newline')as A:
   thewriter = cav.writer(A)
thewriter.writerow({'11 Wall Street, New York, NY, 10005'})
thewriter.writerow({'350 Fifth Avenue, New York, NY, 10118'})
thewriter.writerow({'1600 Pennsylvania Avenue NW, Washington DC, 20500'})
thewriter.writerow({'4059 Mt Lee Dr.,Hollywood, CA, 90068'})
thewriter.writerow({'Statue of Liberty, Liberty Island, New York, NY, 10004'})
thewriter.writerow({'1313 Mockingbird Lane, Albany, NY, 12084'})
thewriter.writerow({'0001 Cemetery Lane, Westfield, NJ, 07091'})
thewriter.writerow({'3109 Grant Ave, Philadelphia , Pa, 19114'})
thewriter.writerow({'532 N. 7th Street, Philadelphia, PA, 19123'})
thewriter.writerow({'317 Chestnut Street, Philadelphia, PA, 19106'})

TypeError: 'str' object cannot be interpreted as an integer

any help would be appericated

I just need it to print the information I entered.

CodePudding user response:

open does not take an argument 'newline' which is a string. It can take a keyword argument newline =. As the documentation says: newline determines how to parse newline characters from the stream. It can be None, '', '\n', '\r', and '\r\n'.

CodePudding user response:

The issue is with how you call the open() function.

# This call will result in TypeError
with open('myaddresses.csv','w','newline')as A:
   # do something with file A

The argument 'newline' isn't assigned properly. If we look at the function definition:

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

As you call the open() function with positional arguments only, you are trying to assign the value 'newline' to buffering which only accepts an integer.

The proper way to call open() in your case would be to use the keyword argument for newline, that is:

with open('myaddresses.csv', 'w', newline="\n") as A:
    # do something with file A

The newline argument can be only one of the following:

None, '', '\n', '\r', and '\r\n'.

The default value for the newline argument is None.

  • Related