0

I am doing a class project and for that I am trying to use a function, where it produce conditional output every time depending on the basis of user input. And I want that output to be store in a file automatically every time it produces the result. Am not sure how to do that. Could someone please help me here. below is the code I am working on:

def server_temp(prompt, value_min,value_max):
  while True:
    number_text = input(prompt)
    try:
      number = int(number_text)
    except ValueError:
      print('Invalid number text. Please enter digits.')
      #continue loop and return to the top of the loop
    if number<=value_min:
      print('the room has correct temperature')
      return number
    if number>=value_max:
      print(' the room has very hot temerature ')
      return number
   
#function calling 
server_temp('What is the server room temperature?:',value_min = 21-23,value_max = 24-30)

temp_record= open("room temp record.txt",'w')
temp_record.write('')
temp_record.close()
  • Googling "Python Write to file" leads to [the relevant part of the Python Documentation](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files) and also to [some](https://www.w3schools.com/python/python_file_write.asp) [tutorials](https://www.guru99.com/reading-and-writing-files-in-python.html). Do these links answer your question? If not, where are you stuck exactly? – Jonathan Scholbach Feb 16 '21 at 05:37
  • @jonathan.scholbach I did googled it but can't seem to find the answer where it tells you to how to add the output into a file automatically. Will have a look on your referred links. – GhostwhiteActualCompilers Feb 16 '21 at 05:41
  • Seems you're missing out on `continue` in place of `#continue loop and return to the top of the loop`. – theProcrastinator Feb 16 '21 at 05:56

1 Answers1

0

Seems like you're looking for "Append"

 f = open('workfile', 'a')

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. the mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

with open("room temp record.txt,"a") as f:
                f.write("\n")
                f.writelines(["Min temp","Max temp"])
Geom
  • 1,491
  • 1
  • 10
  • 23
  • not exactly. the above code is writing those line every time it executes. Whereas I am looking to overwrite those lines with the latest output every time it execute. Thanks anyways for helping – GhostwhiteActualCompilers Feb 16 '21 at 05:58