I am having problems with this bit of code
import csv
temp = open("townsfile.csv", "r")
towns = temp.read()
temp.close()
print(towns)
eachTown = towns.split("\n")
print (eachTown)
record = eachTown.split(",")
for line in eachTown:
record = eachItem.split(",")
print(record)
newlist=[]
newlist.append(record)
newlist=[]
for eachItem in eachTown:
record = eachItem.split(",")
newlist.append(record)
print(newlist)
It returns this error
Traceback (most recent call last):
File "N:/Python practice/towns.py", line 10, in <module>
record = eachTown.split(",")
AttributeError: 'list' object has no attribute 'split'
Can anyone help me with this
The csv
module gives you this text parsing functionality, you do not need to do it yourself.
import csv
with open("townsfile.csv", "r") as f:
reader = csv.reader(f, delimiter=',')
towns = list(reader)
print(towns)
The problem you have is that list.split()
does not exist, you are trying to use str.split()
but you already split it into a list
of str
s. You would need to do it for every str
in the list.
eachTown = towns.split("\n")
This code return list. List don't have attribute split. You should replace
record = eachTown.split(",")
like this
records = [rec.split(",") for rec in eachTown]
But better if you start using module csv for read this file.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.