代码之家  ›  专栏  ›  技术社区  ›  SoulFanatic

Python附加不工作

  •  0
  • SoulFanatic  · 技术社区  · 7 年前

    因此,这段代码大部分是我自己的,很抱歉它可能写得一团糟和/或很糟糕,但我的问题是为什么要写这些行

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End") 
    

    无论何时调用,都不会在文件底部追加“End”。

    import time
    
    def replace_all(text, rps):
        for i, j in rps.items():
            text = text.replace(i, j)
        return text
    
    def replacer():
        inf = "hScrape.txt"
        ouf = "hPROC.txt"
        A = open(inf, "r")
        B = open(ouf, "w")
        reps = {"Result Date:":"", "Draw Result:":"", "Bonus":"", "January":"", "February":"", "March":"", "April":"", "May":"", "June":"", "July":"", "August":"", "September":"", "October":"", "November":"", "December":"", "With Max Millions!":"", "2009":"", "2010":"", "2011":"", "2012":"", "2013":"", "2014":"", "2015":"", "2016":"", "2017":"", "2018":"", "30th":"", "29th":"", "28th":"", "27th":"", "26th":"", "25th":"", "24th":"", "23rd":"", "22nd":"", "21st":"", "20th":"", "19th":"", "18th":"", "17th":"", "16th":"", "15th":"", "14th":"", "13th":"", "12th":"", "11th":"", "10th":"", "9th":"", "8th":"", "7th":"", "6th":"", "5th":"", "4th":"", "3rd":"", "2nd":"", "1st":"", "\t":""}
        txt = replace_all(A.read(), reps)
        B.write(txt)
        A.close
        B.close
    
        D = open("C:\\aPATH\\hPROC.txt", "a")
        D.write("End")
    
        C = open("C:\\aPATH\\Result.txt", "w+")
        print("Completed Filtering Sequence")
        time.sleep(3)
    
    
        while True:
            B = open("hPROC.txt", "r")
            z = B.readline()
            print(z)
            if "End" in z:
                C.write("DN")
                break
            else:
                if z != "\n":
                    if " " not in z:
                        if int(z) < 10:
                            C.write("0" + z)
                        else:
                            C.write(z)
    
    replacer()
    
    3 回复  |  直到 7 年前
        1
  •  0
  •   HunterM267    7 年前

    由于Python文件缓冲系统的工作方式,当打开一个文件并附加到它,但不关闭或刷新它时,附加的行不一定会被写入。

    看见 this 有关flush功能的更多信息。

    因此,代码的解决方案就是将其更改为

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End")
    D.close()
    

    此外,如果您打算附加更多内容,以便稍后关闭文件,则可以制作该代码段

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End")
    D.flush()
    

    (使文件保持打开状态,并将内部缓冲区刷新到操作系统缓冲区)。

        2
  •  0
  •   Edwin van Mierlo    7 年前

    您忘记用关闭文件 D.close()

    这个 close() 将关闭文件,并写入缓冲区中可能延迟的所有数据。

    如果不想关闭文件,则需要“刷新”两次,例如

    D.flush()
    os.fsync(D.fileno())
    

    对于以后的,请执行 import os ,这将刷新此文件的操作系统缓冲区。

        3
  •  0
  •   Dharman Aman Gojariya    3 年前

    目前为止,我找到的最佳方法如下:

    with open("your text file") as f:
        for line in f:
            if "your text to append" in line.rstrip('\r\n'):
               print("Exists!")
               break
        else:
            f.write("your text to append" + "\n")