Python-write()添加我没有添加的内容';别指望

Python-write()添加我没有添加的内容';别指望,python,python-2.7,Python,Python 2.7,我正在使用文件I/O函数,在写入文件时遇到问题 为了了解它,我要么在一个范围上运行for循环,将每个循环添加到一个新行,要么对一个列表执行相同的操作。无论哪种方式,我都会在循环后将以下内容附加到文件中: 98 99 is dropped. """ global quitting try: raise except SystemExit: raise except EOFE

我正在使用文件I/O函数,在写入文件时遇到问题

为了了解它,我要么在一个范围上运行for循环,将每个循环添加到一个新行,要么对一个列表执行相同的操作。无论哪种方式,我都会在循环后将以下内容附加到文件中:

98
99
is dropped.

"""

        global quitting

        try:

            raise

        except SystemExit:

            raise

        except EOFError:

            global exit_now

            exit_now = True

            thread.interrupt_main()

        except:

            erf = sys.__stderr__

            print>>erf, '\n' + '-'*40

            print>>erf, 'Unhandled server exception!'

            print>>erf, 'Thread: %s' % threading.currentThread().getName()

            print>>erf, 'Client Address: ', client_address

            print>>erf, 'Request: ', repr(request)

            traceback.print_exc(file=erf)

            print>>erf, '\n*** Unrecoverable, server exiting!'

            print>>erf, '-'*40

            quitting = True

            thread.interrupt_main()



class MyHandler(rpc.RPCHandler):



    def handle(self):

        """Override base method"""

        executive = Executive(self)

        self.register("exec", executive)

        self.console = self.get_remote_proxy("console")

        sys.stdin = PyShell.PseudoInputFile(self.console, "stdin",

                IOBinding.encoding)

        sys.stdout = PyShell.PseudoOutputFile(self.console, "stdout",

                IOBinding.encoding)

        sys.stderr = PyShell.PseudoOutputFile(self.console, "stderr",

                IOBinding.encoding)



        # Keep a reference to stdin so that it won't try to exit IDLE if

        # sys.stdin gets changed from within IDLE's shell. See issue17838.

        self._keep_stdin = sys.stdin



        self.interp = self.get_remote_proxy("interp")

        rpc.RPCHandler.getresponse(self, myseq=None, wait=0.05)



    def exithook(self):

        "override SocketIO method - wait for MainThread to shut us down"

        time.sleep(10)
        <ad nauseum>
但即使我关闭它并打开文件本身,这些东西也会被附加


如果没有这些额外的东西,我如何将数据写入文件?

为什么要使用
'w+'
作为文件模式进行写入?您是否尝试过先截断文件,我怀疑您只是部分覆盖了现有文件。作为一种风格说明,在打开文件时,您应该始终使用带有语法的python,例如使用open('test.txt.'w+')的
作为f:
这确保文件在处理完毕后关闭。您将丢失
\n
之后的结束引号。因此,脚本的其余部分都被写入到文件中。这是真实脚本中缺少的引号,还是复制错误?即使忽略@Barmar的观察,
读取
也不会返回任何内容,因为文件指针位于文件的末尾。这真的是导致问题的代码吗?
f = open('test.txt', 'w+')
for x in range(100):
    f.write((str(x) + '\n'))
f.read()