因此,大部分代码都是我自己的,对于这可能是一团糟和/或可怕的事实表示道歉,但我的问题是为什么这些行
D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("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()
答案 0 :(得分:0)
由于Python的文件缓冲系统的工作方式,当打开文件并附加到文件但没有关闭或刷新文件时,附加的行不一定要写。
有关flush的内容的更多信息,请参阅this。
因此,代码的解决方案只是将其更改为
D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("End")
D.close()
另外,如果您打算追加更多文件并在以后关闭该文件,则可以制作该片段
D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("End")
D.flush()
(使文件保持打开状态,并将内部缓冲区刷新到OS缓冲区)。
答案 1 :(得分:0)
您忘记使用D.close()
close()
将关闭文件,并写入可能在缓冲区中延迟的所有数据。
如果您不想关闭文件,则需要&#34; flush&#34;两次,例子
D.flush()
os.fsync(D.fileno())
对于后者,请执行import os
,这将刷新此文件的os缓冲区。