0

1.This is the correct code

def game():
    return 56
c = game()
with open("PS_9-2.txt") as a: 
    b = a.read()
if(b == ""):
    with open("PS_9-2.txt","w") as a: 
        a.write(str(c))
elif(int(b) < c):
    with open("PS_9-2.txt","w") as a: 
        a.write(str(c))

2.This is the wrong one but why ?

def game():
    return 5
c = game()
with open("PS_9-2.txt") as a:
    b = a.read()
with open("PS_9-2.txt","w") as a: # is this the wrong way 
    if(b == ""):
            a.write(str(c))
    elif(int(b) < c):
            a.write(str(c))

I was expecting same output for both the code but the second code only writes when the PS_9-2.txt file is empty or the value specified in the function is greater when I provide a smaller value it just gets all clear in the text file

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • what output you got in the first way? – The6thSense Jan 06 '23 at 05:44
  • 1
    Welcome to Stack Overflow. Please read [ask] and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and [mre]. Make sure that we can **copy and paste** from the example, **without changing anything**, and **directly** see the **exact** problem. This means: show how to create the original `PS_9-2.txt` file; explain step by step **for a case where the result is wrong** what you expect to happen and what happens instead. "It just gets all clear in the text file" is not understandable. Show what the text file contains afterwards, for both the correct code and the wrong code. – Karl Knechtel Jan 06 '23 at 05:44
  • Next: try to find a problem yourself by using a debugger, or at least by using `print` to check values in the program step by step. For example, you should be able to check what the result is from the conditions that each `if` or `else` statement is computing. Also check: what else happens differently in the two pieces of code? For example, **does the file get opened** by one version of the code, but not the other? (Do you understand what happens to the existing contents in a file, when it is opened for writing?) – Karl Knechtel Jan 06 '23 at 05:47
  • Does [Difference between modes a, a+, w, w+, and r+ in built-in open function?](/questions/1466000) answer your question? – Karl Knechtel Jan 06 '23 at 05:49
  • As an aside: **please** update to a modern version of Python. For **more than three years now**, all 2.x versions of Python have been **not supported**. They will receive no more security fixes or any other maintenance. They are about as far out of date as Windows 7. – Karl Knechtel Jan 06 '23 at 05:50

1 Answers1

0

In the 1st block you open a file and read it, then only after deciding if you need to write do you open the file again in write mode and write to it.

In the 2nd block you open the file and read it, then open the file in write mode before deciding whether to write or not.

The important bit here is opening in write mode truncates existing files.

Lee
  • 149
  • 1
  • 8