Python 2.7:整个代码写入文件问题

时间:2015-01-29 00:18:53

标签: python file python-2.7 canopy writing

我是一个简单的问题。在程序中 - 程序并不重要 - 只有第一行,我打开一个空文件(名为empty.txt)。 然后我定义了函数,但从不在main上使用它们......所以,我实际上并没有写任何东西。

这几乎完整的代码:

from os import chdir

chdir('C:\\Users\\Julien\\Desktop\\PS BOT')

fic=open('empty.txt','r+')

def addtodic(txt):
    """Messages de la forme !add id,message ; txt='id,message' """
    fic.write(txt+'\n')
    fic.seek(0)

def checkdic(txt):
    """Messages de la forme !lien id ; txt='id' """
    for i in fic.readlines().split('\n'):
        ind=i.index(',')
        if i[:ind]==txt:
            fic.seek(0)
            return i[ind+1:]
    fic.seek(0)
    return 'Not found'

然后我启动它,并使用控制台,我只是问" fic.write(' tadam')",比如,在继续之前检查写作是否有效

%run "C:/Users/Julien/Desktop/PS BOT/dic.py"

fic
Out[8]: <open file 'empty.txt', mode 'r+' at 0x0000000008D9ED20>

fic.write('tadam')

fic.readline()
Out[10]: 'os import chdir\n'

fic.readline()
Out[11]: "chdir('C:\\\\Users\\\\Julien\\\\Desktop\\\\PS BOT')\n"

fic.readline()
Out[12]: '\n'

fic.readline()
Out[13]: "fic=open('empty.txt','r+')\n"

fic.readlines()
Out[14]:
['\n',
 'def addtodic(txt):\n',
 '    """Messages de la forme !add id,message ; txt=\'id,message\' """\n',
 '    fic.seek(0)\n',
 "    fic.write(txt)+'\\n'\n",
 '\n',
 'def checkdic(txt):\n',
 '    """Messages de la forme !lien id ; txt=\'id\' """\n',
 "    for i in fic.readline().split('\\n'):\n",
 "        ind=i.index(',')\n",
 '        if i[:ind]==txt:\n',
 '            fic.seek(0)\n',
 '            return i[ind+1:]\n',
 '    fic.seek(0)\n',
 "    return 'Not found'\n",
 '    \n',
 'def removedic(txt):\n',
 '    """Messages de la forme !remove id ; txt=\'id\' """\n',
 '    check=True\n',
 '    while check:\n',
 '        i=fic.readline()\n',
 '        if i[:len(txt)]==txt:            \n',
 '            fic.seek(0)\n',
 '            return check\n',
 '#removedic fauxeturn check\r\n',
 "#removedic faux    tmp_file = open(filename,'w')\n",
 '            tmp_file.write(data)\n',
 '            tmp_file.close()\n',
 '        return filename\n',
 '\n',
 '    # TODO:  This should be removed when Term is refactored.\n',
 '    def write(self,data):\n',
 '        """Write a string to the default output"""\n',
 '        io.stdout.write(data)\n',
 '\n',
 '    # TODO:  This should be removed when Term is refactored.\n',
 '    def write_err(self,data):\n',
 '        """Write a string to the default error output"""\n',
 '        io.stderr.write(data)\n',
 '\n',
 '    def ask_yes_no(self, prompt, default=None):\n',
 '        if self.quiet:\n',
 '            return True\n',
 '        return ask_yes_no(prompt,default)\n',
 '\n',
 '    def show_usage(self):\n',
 '        """Show a usage message"""\n',
 '        page.page(IPython.core.usage.interactive_usage)\n',
 '\n',
 '    def extract_input_lines(self, range_str, raw=False):\n',
 '        """Return as a string a set of input history slices.\n',
 '\n',
 '        Parameters\n',
 '        ----------\n',
 '        range_str : string\n',
 '            The set of slices is given as a string, like "~5/6-~4/2 4:8 9",\n',
 '            since this function is for use by magic functions which get their\n',
 '            arguments as strings. The number before the / is the session\n',
 '            number: ~n goes n back from the current session.\n',
 '\n',
 '        Optional Parameters:\n',
 '          - raw(False): by default, the processed input is used.  If this is\n',
 '          true, the raw input history is used instead.\n',
 '\n',
 '        Note that slices can be called with two notations:\n',
 '\n',
 '        N:M -> standard python form, means including items N...(M-1).\n',
 '\n',
 '        N-M -> include items N..M (closed endpoint)."""\n',
 '        lines = self.history_manager.get_range_by_str(range_str, raw=raw)\n',
 '        return "\\n".join(x for _, _, x in lines)\n',
 '\n',
 '    def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):\n',
 '        """Get a code string from history, file, url, or a string or macro.\n',
 '\n',
 '        This is mainly used by magic functions.\n',
 '\n',
 '        Parameters\n',
 '        ----------\n',
 '\n',
 '        target : str\n',
 '\n',
 '          A string specifying code to retrieve. This will be tried respectively\n',
 '          as: ranges of input history (see %history for syntax), url,\n',
 '          correspnding .py file, filename, or an expression evaluating to a\n',
 '          string or Macro in the user namespace.\n',
 '\n',
 '        raw : bool\n',
 '          If true (default), retrieve raw history. Has no effect on the other\n',
 '          retrieval mechanisms.\n',
 '\n',
 '        py_only : bool (default False)\n',
 '          Only try to fetch python code, do not try alternative methods to decode file\n',
 '          if unicode fails.\n',
 '\n',
 '        Returns\n',
 '        -------\n',
 '        A string of code.\n',
 '\n',
 '        ValueError is raised if nothing is found, and TypeError if it evaluates\n',
 '        to an object of another type. In each case, .args[0] is a printable\n',
 '        message.\n',
 '        """\n',
 '        code = self.extract_input_lines(target, raw=raw)  # Grab history\n',
 '        if code:\n',
 '            return code\n',
 '        utarget = unquote_filename(target)\n',
 '        try:\n',
 "            if utarget.startswith(('http://', 'https://')):\n",
 '                return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)\n',
 '        except UnicodeDecodeError:\n',
 '            if not py_only :\n',
 '                from urllib import urlopen  # Deferred import\n',
 '                response = urlopen(target)\n',
 "                return response.read().decode('latin1')\n",
 '            raise ValueError(("\'%s\' seem to be un']

KABOOM!有人解释一下吗?顺便说一句,我使用Python 2.7和Enthought Canopy。

1 个答案:

答案 0 :(得分:0)

当您使用'r+'打开文件时,它不会被截断,它仍会保留其旧内容。要将其截断为0字节,请在打开后立即调用fic.truncate(0)

您必须在同一文件对象上进行读写操作(否则结果因缓冲而未定义),例如:在fic.seek(0, 0)来电后添​​加write(或任何其他搜索)。