我有这个:
class books:
def __init__(self,id,title,author,avaliable):
self.id=id
self.title=title
self.author=author
self.avaliable=avaliable
def __str__ (self):
return ('id: '+self.id+'\ntitle:'+self.title+'\nauthor: '+self.author+'\nauthor: '+self.author+'\navaliable:' + self.avaliable)
def __getitem__(self,i):
return self.title
with open ('txt.txt','r') as f:
lines=f.readlines()
bo=[]
for line in lines:
line = line.strip()
book = line.split(';')
s = books(book[0],book[1],book[2],book[3])
bo.append(s)
bo=books()
bo.id=book[0]
bo.title=book[1]
bo.author=book[2]
bo.avaliable=book[3]
尝试从文件中读取列表中的每个元素。目前代码正在给出错误:
Traceback (most recent call last):
File "T:/semester 2/programming/coursework/classes with array most recent.py", line 17, in <module>
s = books(book[0],book[1],book[2],book[3])
IndexError: list index out of range
在我的txt文档中,程序应分别读取四列以获取每行的四个值的列表。因此程序应该能够访问列表的每个部分,但目前它已超出范围。我想知道如何改变这一点的任何提示或提示,谢谢。
txt文件读作:
1;Book_1;Author_1;0
2;Book_2;Author_2;0
3;Book_3;Author_3;0
4;Book_4;Author_4;0
5;Book_5;Author_5;0
6;Book_5;Author_5;0
7;Book_7;Author_7;0
8;Book_8;Author_8;0
9;Book_9;Author_9;0
10;Book_10;Author_10;0
答案 0 :(得分:2)
您说文件包含的内容(;
)与脚本读取时文件实际包含的内容之间存在差异(\t
=制表符,\\t
=序列字符\
和t
)
您可以将csv.reader与正确的分隔符一起使用,或者如果您坚持手动分割,请使用:
book = line.split('\t')
或者如果文件字面上包含\t
,则使用:
book = line.split('\\t')