我有一个带有数字和名称的文本文件,格式如下:
129308123, Some Name
12390123, Some Other Name
我正在尝试获取此文本文件中的最大数字,并阅读它所在的行。我尝试了多种方法,但似乎没有一种方法适合我。我做错了什么?
我的代码:
file_in = open('kaartnummers.txt', 'r')
regels = len(file_in.readlines())
smallestInt = 0
intList = [int(x) for x in file_in.readlines()]
number = max(intList)
laatsteregel = ''
string_format = 'Deze file telt {0} regels\n' \
'Het grootste kaartnummer is: {1} en dat staat op regel {2}'
result = string_format.format(regels, number, laatsteregel)
print(result)
答案 0 :(得分:0)
要查找文件中的最大数字,请使用split
file_in = open('kaartnummers.txt', 'r')
smallestInt = 0
intList = [int(x.split(",")[0]) for x in file_in.readlines()]
print(intList)
regels = len(intList)
number = max(intList)
laatsteregel = ''
string_format = 'Deze file telt {0} regels\n' \
'Het grootste kaartnummer is: {1} en dat staat op regel {2}'
result = string_format.format(regels, number, laatsteregel)
print(result)
<强> kaartnummers.txt 强>
11, Bob
22, James
33, Nick
23, Steve
25, John
21, Ken
输出
python pyprog.py
[11, 22, 33, 23, 25, 21]
Deze file telt 6 regels
Het grootste kaartnummer is: 33 en dat staat op regel
要获取行号,您可以使用此代码(记住它从0开始)
print("line number " + str(intList.index(max(intList))))