簡體   English   中英

Python:“ Return True”后如何繼續覆蓋代碼

[英]Python: How to continue overwrite the code after “Return True”

以下是基本功能:

CheckReady.txt文件中,可以為10

讀取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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM