我尝试切片文件中的列表,但是它仍然没有返回正确的行数,应该是4051。
我的代码:
def readData(filename):
inputFile = open(filename, 'r')
inputFile.readline()
playerList = []
for line in inputFile:
fields = line.split(",")
playerList.append(fields[1:4052])
inputFile.close()
return playerList
答案 0 :(得分:1)
fields[1:4052]
对每一行的字段进行切片,而不对文件中的行进行切片。
如果只需要文件的前4051行,请使用range(4051)
来读取这些行。
def readData(filename):
playerList = []
with inputFile as open(filename):
inputFile.readline() # skip headers
for _ in range(4051):
line = inputFile.readline()
if not line:
break
fields = line.split(",")
playerList.append(fields)
return playerList
答案 1 :(得分:0)
假设4051并不是神奇的,OP只是担心读取结果与他们所知道的行数不匹配,这是一个更简洁的版本(可能还建议read_players可能更具描述性函数名称):
def readData(filename):
with open(filename, 'r') as inputFile:
inputFile.readline() # skip headers
playerList = [line.strip().split(',') for line in inputFile]
return playerList