脚本反向写入

时间:2016-06-30 20:39:51

标签: python python-3.x

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

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

4 个答案:

答案 0 :(得分:2)

很好的谜题。为什么这些线路反向出现?由于输出缓冲:

写入文件时,系统不会立即将数据提交到磁盘。这种情况会定期发生(当缓冲区已满时),或文件关闭时。您永远不会关闭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. 如果你想要随时写,你应该只打开文件一次,反复写,然后在完成后关闭它。

答案 1 :(得分:1)

您需要在写入之后关闭文件,然后再尝试再次打开它。否则,在程序关闭之前,您的写入将不会完成。

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

答案 2 :(得分:0)

如果替换:

f = open(usrtxtdir,"a")
f.write(words + '\n')

使用:

with open(usrtxtdir,"a") as f:
    f.write(words + '\n')

它按顺序出现。几乎总是使用with open()进行文件访问。即使在崩溃的情况下,它也会自动为您处理文件的关闭。虽然您可能会考虑在内存中处理文本并仅在退出时编写它。但这并不是手头问题的一部分。

答案 3 :(得分:0)

Python的file.write()文档指出:“由于缓冲,在调用flush()close()方法之前,字符串实际上可能不会显示在文件中”

由于你在递归文件并在关闭它之前写入文件(或刷新缓冲区),因此在内部框架(你写的'时)尚未写入外部值('嗨,我的名字')是bob。')完成,它似乎自动刷新写缓冲区。

你应该能够添加file.flush()来纠正它:

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')
    f.flush() # <-----   ADD THIS LINE HERE   -----< #
    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()

另外,完成后请不要忘记关闭文件!