[英]Python: How to continue overwrite the code after “Return True”
以下是基本功能:
在CheckReady.txt
文件中,可以為1
或0
讀取1
,應返回True,然后將1
替換為0
以完成重置
如果讀取0
,則它將返回false。
下面是我的代碼:
def CheckReady():
s = open("CheckReady.txt").read()
print "Ready= ",s
if s == "1":
print "ready"
return True
s = s.replace("1", "0");
f = open ("TrakStarReady.txt",'w')
f.write(s)
print "Ready= ",s, "Reset Complete"
elif s == "0":
print "not ready"
return False
f.close()
這是我的問題:
我知道return True
,代碼將停止執行將1
替換為0
...我真的是編程新手...嘗試過很多次,但不知道如何解決。
有人可以幫我解決此問題並完成基本功能嗎?
做您想做的所有事情,然后返回:
def CheckReady():
with open("CheckReady.txt") as check:
s = check.read()
print "Ready= ",s
if s == "1":
print "ready"
s = "0"
with open("TrakStarReady.txt",'w') as trak:
trak.write(s)
print "Ready= ",s, "Reset Complete"
return True
else:
print "not ready"
return False
您不需要打開CheckReady文件。 而是將文件用作“標記”。 如果您還沒准備好,請將文件移到臨時位置。 准備就緒后,對其進行重命名。
這是我要改進的方法:
import os
def CheckReady():
if os.path.isfile('/my/path/ready.txt'):
# the file exists. Reset the marker
os.rename('/my/path/ready.txt', '/my/path/notready.txt')
with open ("TrakStarReady.txt",'w'):
f.write(1)
return True
else:
print "not ready"
return False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.