尝试读取.txt文件,然后将其信息转换为对象:
class HeaderReader:
@staticmethod
def headerFromFile(filePath):
with open(filePath, 'r') as file:
headerList = HeaderList()
headerFile = ''
for element in range(7):
headerFile += file.readline()
tempList= headerFile.rstrip().split('\n')
#tempList= ['Company:', 'Things', 'Day:', '07:11:1987', 'Time:', '15:55', 'Transfers:']
for splittedEls in tempList:
header = Header(
splittedEls[0],
splittedEls[1],
splittedEls[2],
splittedEls[3],
splittedEls[4],
splittedEls[5],
splittedEls[6]
)
headerList.append(header)
return headerList
正常工作直至达到splittedEls[4]
,即'时间:'返回IndexError: string index out of range
这对我来说毫无意义。标题类只是标准的7个参数类,如果需要将发布。知道问题是什么吗?
答案 0 :(得分:0)
我愚蠢,我认为第二个循环是错误的,认为这有效:
class HeaderReader:
@staticmethod
def headerFromFile(filePath):
with open(filePath, 'r') as file:
headerList = HeaderList()
headerFile = ''
for element in range(7):
headerFile += file.readline()
tempList = headerFile.rstrip().split('\n')
header = Header(
tempList[0],
tempList[1],
tempList[2],
tempList[3],
tempList[4],
tempList[5],
tempList[6]
)
return header