简体   繁体   中英

find the smallest number in a text file (python)

So I have a text file with roughly 400 lines, each line has a number and I need to find the smallest of these numbers.

I currently have

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

But it doesnt work for some reason. What would be the best way to get the smallest number in the .txt file? (fread is the .txt file that I have opened in main() function! And I will write the number to fwrite, once I manage to figure it out lol)

EDIT: I get an error (ValueError) at the smallest = min(number) part saying "min() arg is an empty sequence".

EDIT2: I am using a test.txt file to test the code first before, and its just

1000 700 450 200 100 10 1 on different lines each So the same format/type as the file I am supposed to use

fread (where I get the numbers) and fwrite (where i want to save the numbers) are defined as follows in 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

I'm sorry for possible bad "formating" etc of this question, I am new to python and StackOverflow!

Thanks for the help!

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])

I did not run the code, but it should work. It would be best if you had more error-checking. For example, int(line) could throw an exception if line is not a number.

Your code does not work because list comprehensions should use square brackets instead of curly brackets.

It should be [int(line) for line in fread] and not {int(line) for line in fread}

Once you have a list the function min also will work.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM