我遇到了这段代码的问题
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)
它返回此错误
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'
任何人都可以帮助我吗
答案 0 :(得分:0)
eachTown = towns.split("\n")
此代码返回列表。列表没有属性拆分。你应该替换
record = eachTown.split(",")
像这样
records = [rec.split(",") for rec in eachTown]
但如果您开始使用module csv来阅读此文件,那就更好了。
答案 1 :(得分:0)
csv
模块为您提供了此文本解析功能,您无需自己动手。
import csv
with open("townsfile.csv", "r") as f:
reader = csv.reader(f, delimiter=',')
towns = list(reader)
print(towns)
您遇到的问题是list.split()
不存在,您尝试使用str.split()
,但您已将其拆分为list
个str
。您需要为列表中的每个str
执行此操作。