Python - write()添加我没想到的内容

时间:2016-03-02 16:48:29

标签: python python-2.7

我正在使用文件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>

创建此代码的代码是:

f = open('test.txt', 'w+')
for x in range(100):
    f.write((str(x) + '\n'))
f.read()

但即使我关闭它并打开文件本身,也会附加这些内容。

如何在没有这些额外内容的情况下将数据写入文件?

0 个答案:

没有答案