对不起,如果我问错了,或者格式化错了,这是我第一次来这里。基本上,这个脚本是一个非常非常简单的文本编辑器。问题是,当它写入文件时,我希望它写:
Hi, my name
is bob.但是,它写道:
is bob.
Hi, my name我怎么才能解决这个问题?守则如下:
import time
import os
userdir = os.path.expanduser("~\\Desktop")
usrtxtdir = os.path.expanduser("~\\Desktop\\PythonEdit Output.txt")
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return
def lowlevelinput():
cmd = input("\n$ ")
if(cmd == "/edit"):
editor()
elif(cmd == "/citenote"):
print("Well, also some help from internet tutorials.\nBut Brendan did all the scripting!")
lowlevelinput()
print("Welcome to the PythonEdit Basic Text Editor!\nDeveloped completley by Brendan*!")
print("Type \"/citenote\" to read the citenote on the word Brendan.\nType \"/edit\" to begin editing.")
lowlevelinput()发布于 2016-06-30 20:53:57
很好的谜题。为什么这些线是相反的?由于输出缓冲:
当您写入文件时,系统不会立即将数据提交到磁盘。这是定期发生的(当缓冲区已满时),或当文件被关闭时。你从不关闭f,所以当f超出范围时,它就会关闭.这在函数editor()返回时发生。但是editor() 递归地调用自己!因此,对editor()的第一个调用是最后一个退出的调用,其输出是最后一个提交到磁盘的调用。很好,嗯?
要解决此问题,只需在编写完以下内容之后立即关闭f:
f = open(usrtxtdir,"a")
f.write(words + '\n')
f.close() # don't forget the parentheses或相当于:
with open(usrtxtdir, "a") as f:
f.write(words + '\n')但最好是修复您的项目的组织:
editor(),而不是递归调用。发布于 2016-06-30 20:55:28
您需要在编写完文件后,在尝试再次打开它之前关闭它。否则,在程序关闭之前,您的写操作将无法完成。
def editor():
words = input("\n")
f = open(usrtxtdir,"a")
f.write(words + '\n')
nlq = input('Line saved. "/n" for new line. "/quit" to quit.\n$ ')
f.close() # your missing line!
if(nlq == '/quit'):
print('Quitting. Your file was saved on your desktop.')
time.sleep(2)
return
elif(nlq == '/n'):
editor()
else:
print("Invalid command.\nBecause Brendan didn't expect for this to happen,\nthe program will quit in six seconds.\nSorry.")
time.sleep(6)
return发布于 2016-06-30 20:52:43
如果您替换:
f = open(usrtxtdir,"a")
f.write(words + '\n')通过以下方式:
with open(usrtxtdir,"a") as f:
f.write(words + '\n')它是按顺序出来的。几乎总是使用with open()进行文件访问。它自动为您处理文件的关闭,即使在崩溃的情况下也是如此。尽管您可能会考虑在内存中使用文本,并且只在退出时才编写它。但这并不是眼前问题的一部分。
https://stackoverflow.com/questions/38132854
复制相似问题