脚本写反了

2024-06-25 23:34:07 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果我问错了或者格式化错了,这是我第一次来这里。 基本上,这个脚本是一个非常非常简单的文本编辑器。问题是,当它写入文件时,我希望它写入:

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()

Tags: thetocmdinputtimeosmyhi
2条回答

您需要在写入后关闭文件,然后再尝试打开它。否则,在程序关闭之前,您的写入操作将无法完成。你知道吗

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

拼图不错。为什么线是反向的?由于输出缓冲:

写入文件时,系统不会立即将数据提交到磁盘。这种情况会定期发生(当缓冲区已满时),或者当文件关闭时。您从不关闭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')

但最好确定你的项目组织:

  1. 使用循环来运行editor(),而不是递归调用。你知道吗
  2. 编辑器应该在会话结束时写出文件,而不是每行都输入。考虑在一个行列表中收集用户输入,并在最后一次性地写出所有内容。你知道吗
  3. 如果确实要边写边写,应该只打开一次文件,反复写,然后在完成后关闭它。你知道吗

相关问题 更多 >