在文本文件中找到最小的数字 (python)

find the smallest number in a text file (python)

所以我有一个大约有 400 行的文本文件,每行都有一个数字,我需要找到这些数字中最小的一个。

我目前有

def smallestnumber(fread, fwrite):
number = {int(line) for line in fread}
smallest = min(number)
print ("smallest number is", smallest)

但由于某种原因它不起作用。在 .txt 文件中获取最小数字的最佳方法是什么? (fread 是我在 main() 函数中打开的 .txt 文件!我会把数字写到 fwrite 中,一旦我弄明白了 lol)

编辑:我在最小 = min(number) 部分收到一个错误 (ValueError),说“min() arg 是一个空序列”。

EDIT2:我使用 test.txt 文件先测试代码,它只是

1000 700 450 200 100 10 1个 在不同的线路上 因此 format/type 与我应该使用的文件相同

fread(我得到数字的地方)和fwrite(我想保存数字的地方)在main()

中定义如下
name= input("Give the name of the file which to take data from: ")
fread = open(name, "r") #File which is being read
name2= input("Give the name of the file where to save to: ")
fwrite = open(name2, "w") #File which is being typed to

对于这个问题可能存在的错误“格式化”等问题,我很抱歉,我是 python 和 Whosebug 的新手!

感谢您的帮助!

def smallestnumber(fread, fwrite):
    # store the numbers in a list
    numbers = [int(line) for line in fread]
    # sort the list so that the smallest number is the first element of the list
    numbers.sort()
    # print the first element of the list which contains the smallest number 
    print ("smallest number is: {0}".format(numbers[0])

我没有 运行 代码,但它应该可以工作。如果您有更多的错误检查,那将是最好的。例如,如果 line 不是数字,int(line) 可能会抛出异常。

您的代码不起作用,因为列表理解应该使用方括号而不是大括号。

应该是[int(line) for line in fread]而不是{int(line) for line in fread}

一旦有了列表,函数 min 也可以使用。

max=-9999
for line in open('lines.txt').readlines():
  #print(line)
  for word in line.split():
    #print(word,word.isnumeric())
    if word.isnumeric() and int(word)>max:
      max=int(word)
print(max)