我有这个简单的代码,它实际上只是为了帮助我理解 Python I/O 的工作原理:
inFile = open("inFile.txt",'r')
outFile = open("outFile.txt",'w')
lines = inFile.readlines()
first = True
for line in lines:
if first == True:
outFile.write(line) #always print the header
first = False
continue
nums = line.split()
outFile.write(nums[3] + "\n") #print the 4th column of each row
outFile.close()
我的输入文件是这样的:
#header
34.2 3.42 64.56 54.43 3.45
4.53 65.6 5.743 34.52 56.4
4.53 90.8 53.45 134.5 4.58
5.76 53.9 89.43 54.33 3.45
输出按原样打印到文件中,但我也收到错误:
outFile.write(nums[3] + "\n")
IndexError: list index out of range
我假设这是因为它继续读取下一行,尽管不再有任何数据?