Python 3.6 - file.write() 实际上没有写
Python 3.6 - file.write() not actually writing
如果你没有在标题中看到它,这是 Python 3.6
我 运行 遇到一个问题,我 曾经 能够写入文件,但现在我不能。 疯狂的是,这之前工作正常。
我正在尝试追加我的文件(如果它存在),或者写入一个新文件(如果它不存在)。
main_area_text代表下面的div标签文字
<div id="1131607" align="center"
style="width:970px;padding:0px;margin:0px;overflow:visible;text-
align:center"></div>
下面是我的代码:
main_area_text = #this is equal to the html text above
#I've verified this with a watch during debugging
#But this doesn't actually matter, because you can put
#anything in here and it still doesn't work
html_file_path = os.getcwd() + "\data\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
actual_file = open(html_file_path, "a")
actual_file.write(main_area_text)
else:
print("File does not exist!")
actual_file = open(html_file_path, "w")
actual_file.write(main_area_text)
早些时候,在它的工作状态下,我可以 create/write/append 到 .html 和 .txt 文件。
NOTE: If the file doesn't exist, the program still creates a new file... It's just empty.
我对 python 语言有些陌生,所以我意识到我很可能会忽略一些简单的事情。 (这实际上就是我编写这段代码的原因,只是为了让自己熟悉 python。)
提前致谢!
由于您没有关闭文件,因此数据没有刷新到磁盘。试试这个:
main_area_text = "stuff"
html_file_path = os.getcwd() + "\data\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
with open(html_file_path, "a") as f:
f.write(main_area_text)
else:
print("File does not exist!")
with open(html_file_path, "w") as f:
f.write(main_area_text)
python with statement 将处理将数据刷新到磁盘并自动关闭数据。通常在处理文件时使用 with
是个好习惯。
如果你没有在标题中看到它,这是 Python 3.6
我 运行 遇到一个问题,我 曾经 能够写入文件,但现在我不能。 疯狂的是,这之前工作正常。
我正在尝试追加我的文件(如果它存在),或者写入一个新文件(如果它不存在)。
main_area_text代表下面的div标签文字
<div id="1131607" align="center"
style="width:970px;padding:0px;margin:0px;overflow:visible;text-
align:center"></div>
下面是我的代码:
main_area_text = #this is equal to the html text above
#I've verified this with a watch during debugging
#But this doesn't actually matter, because you can put
#anything in here and it still doesn't work
html_file_path = os.getcwd() + "\data\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
actual_file = open(html_file_path, "a")
actual_file.write(main_area_text)
else:
print("File does not exist!")
actual_file = open(html_file_path, "w")
actual_file.write(main_area_text)
早些时候,在它的工作状态下,我可以 create/write/append 到 .html 和 .txt 文件。
NOTE: If the file doesn't exist, the program still creates a new file... It's just empty.
我对 python 语言有些陌生,所以我意识到我很可能会忽略一些简单的事情。 (这实际上就是我编写这段代码的原因,只是为了让自己熟悉 python。)
提前致谢!
由于您没有关闭文件,因此数据没有刷新到磁盘。试试这个:
main_area_text = "stuff"
html_file_path = os.getcwd() + "\data\myfile.html"
if os.path.isfile(html_file_path):
print("File exists!")
with open(html_file_path, "a") as f:
f.write(main_area_text)
else:
print("File does not exist!")
with open(html_file_path, "w") as f:
f.write(main_area_text)
python with statement 将处理将数据刷新到磁盘并自动关闭数据。通常在处理文件时使用 with
是个好习惯。