Python Forum

Full Version: Incorrect code output (File not being created)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,
As a newbie I wrote the following code.
temperatures = [10, -20, -289, 100]

def temp_convert(temperatures):
    with open("temps.txt", 'w') as myfile:
        for c in temperatures:
            if c > -273.15:
                f = c* 9/5 + 32
                myfile.write(str(f) + "\n")  
My understanding is that this will create a file called temps.txt and this file will have 4 temperatures in it.

The code executes without any error messages.

However the file is not being created in the directory.

I am using python 3.7 in the Eclips IDE on windows 7.

I would really appreciate if someone can point out to me where I am going wrong.
You need to call the function and pass the temperatures to it. I would add this at the bottom:

if __name__ == '__main__':
    convert(temperatures)
Hi Thanks for pointing out one of the mistakes.

I have added in the following line of code after myfile.write

temp_convert(temperatures)
Unfortunately its still not working. I am calling the temp_convert function and passing it a value but still there is no output.
Add some print statements to tell what is happening. Say, one after the open file, and one to print each c as you go through the loop.
(Dec-31-2018, 08:38 PM)Hass Wrote: [ -> ]I have added in the following line of code after myfile.write

What indentation did you add it at? It needs to be added flush left, completely unindented.