抱歉,如果我问错了或者格式化错了,这是我第一次来这里。 基本上,这个脚本是一个非常非常简单的文本编辑器。问题是,当它写入文件时,我希望它写入:
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()
您需要在写入后关闭文件,然后再尝试打开它。否则,在程序关闭之前,您的写入操作将无法完成。你知道吗
拼图不错。为什么线是反向的?由于输出缓冲:
写入文件时,系统不会立即将数据提交到磁盘。这种情况会定期发生(当缓冲区已满时),或者当文件关闭时。您从不关闭
f
,因此当f
超出范围时,它将为您关闭。。。当函数editor()
返回时会发生这种情况。但是editor()
递归地调用自己!所以对editor()
的第一个调用是最后一个退出的调用,它的输出是最后一个提交到磁盘的调用。整洁,嗯?你知道吗要解决此问题,只要在完成以下操作后立即关闭
f
:或同等产品:
但最好确定你的项目组织:
editor()
,而不是递归调用。你知道吗相关问题 更多 >
编程相关推荐