私はこの単純なコードを持っています。これは、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
データがなくなったのに次の行を読み続けたからだと思いますか?