[英]Why these both code gives me different output ? Are they not the same
1.這是正確的代碼
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.這是錯誤的,但為什么?
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))
我期待兩個代碼相同的 output 但第二個代碼僅在 PS_9-2.txt 文件為空時寫入,或者當我提供較小的值時 function 中指定的值更大時它只是在文本文件中全部清除
在第一個塊中,您打開一個文件並讀取它,然后只有在決定是否需要寫入之后,您才能再次打開文件以寫入更多並寫入它。
在第二個塊中,您打開文件並讀取它,然后在決定是否寫入之前以寫入方式打開文件。
這里重要的一點是以寫入模式打開截斷現有文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.