Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python2.7:将整个代码写入文件问题_Python_File_Python 2.7_Canopy_Writing - Fatal编程技术网

Python2.7:将整个代码写入文件问题

Python2.7:将整个代码写入文件问题,python,file,python-2.7,canopy,writing,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

我有一个简单的问题。在一个程序中——程序不重要——只有第一行,我打开一个空文件(名为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']
%运行“C:/Users/Julien/Desktop/PS BOT/dic.py”
菲莎
出[8]:
fic.write('tadam')
fic.readline()
输出[10]:“操作系统导入chdir\n”
fic.readline()
Out[11]:“chdir('C:\\\\Users\\\\Julien\\\\Desktop\\\\PS BOT')\n”
fic.readline()
输出[12]:“\n”
fic.readline()
Out[13]:“fic=open('empty.txt','r+')\n”
fic.readlines()
出[14]:
['\n',,
“def addtodic(txt):\n”,
“格式消息!添加id,消息;txt=\'id,消息\'”“\n”,
“fic.seek(0)\n”,
“fic.write(txt)+'\\n'\n”,
“\n”,
“def checkdic(txt):\n”,
““格式消息!连id;txt=\'id\'”“\n”,
“对于fic.readline().split('\\n')中的i:\n”,
“ind=i.index(',')\n”,
'如果i[:ind]==txt:\n',
“fic.seek(0)\n”,
'返回i[ind+1:][\n',
“fic.seek(0)\n”,
“返回‘未找到’\n”,
“\n”,
“def removedic(txt):\n”,
““”格式消息!删除id;txt=\'id\'”\n“,
“check=True\n”,
'检查时:\n',
'i=fic.readline()\n',
'如果i[:len(txt)]==txt:\n',
“fic.seek(0)\n”,
'返回检查\n',
“#已删除的fauxeturn检查\r\n”,
“#removedic faux tmp_file=open(文件名,'w')\n”,
'tmp_file.write(数据)\n',
'tmp_file.close()\n',
'返回文件名\n',
“\n”,
“#TODO:重构术语时应删除此项。\n”,
“def写入(自身,数据):\n”,
“”将字符串写入默认输出“”\n“,
'io.stdout.write(数据)\n',
“\n”,
“#TODO:重构术语时应删除此项。\n”,
“def write_err(自身,数据):\n”,
““”“将字符串写入默认错误输出”“\n”,
'io.stderr.write(数据)\n',
“\n”,
“def ask_yes_no(self、prompt、default=None):\n”,
'如果self.quiet:\n',
'返回真值\n',
'返回询问\u是\u否(提示,默认值)\n',
“\n”,
'def show_用法(self):\n',
““”显示使用情况消息”“\n”,
'page.page(IPython.core.usage.interactive\u用法)\n',
“\n”,
'def extract_input_lines(自身、范围、原始值=False):\n',
““”“以字符串形式返回一组输入历史切片。\n”,
“\n”,
'参数\n',
'-------------\n',
'范围\u str:string\n',
'切片集以字符串形式给出,如“~5/6-~4/2 4:8 9”,\n',
'由于此函数是供获取其\n'的魔术函数使用的',
'参数为字符串。/前面的数字是会话\n',
'编号:~n从当前会话返回。\n',
“\n”,
'可选参数:\n',
'-raw(False):默认情况下,将使用已处理的输入。如果为\n',
'为true,将使用原始输入历史记录。\n',
“\n”,
'请注意,可以使用两个符号调用切片:\n',
“\n”,
'N:M->标准python表单,表示包含项N.。(M-1)。\N',
“\n”,
'N-M->包含项目N..M(闭合端点)。“”“\N”,
'lines=self.history\u manager.get\u range\u by\u str(range\u str,raw=raw)\n',
“return”\\n.join(x代表行中的x)\n”,
“\n”,
'定义查找用户代码(self、target、raw=True、py\u only=False、skip\u encoding\u cookie=True):\n',
““”“从历史记录、文件、url或字符串或宏中获取代码字符串。\n”,
“\n”,
'这主要由魔术函数使用。\n',
“\n”,
'参数\n',
'-------------\n',
“\n”,
'目标:str\n',
“\n”,
'指定要检索的代码的字符串。将分别尝试此操作\n',
'as:输入历史记录的范围(有关语法,请参阅%history),url,\n',
'corresponding.py文件、文件名或计算为\n'的表达式,
'用户命名空间中的字符串或宏。\n',
“\n”,
'raw:bool\n',
'如果为true(默认值),则检索原始历史记录。对其他记录没有影响\n',
'检索机制。\n',
“\n”,
'py_only:bool(默认为False)\n',
'仅尝试获取python代码,不要尝试其他方法来解码文件\n',
'如果unicode失败。\n',
“\n”,
'返回\n',
'----\n',
'一个代码字符串。\n',
“\n”,
'如果未找到任何内容,则引发ValueError;如果计算结果为TypeError,则引发TypeError\n',
'到另一类型的对象。在每种情况下,.args[0]都是可打印的\n',
'消息。\n',
““”“\n”,
'code=self.extract_input_line(target,raw=raw)#获取历史\n',
'如果代码为:\n',
'返回代码\n',
“utarget=unquote\u文件名(目标)\n”,
'尝试:\n',
“如果utarget.startswith(('http://','https://'):\n”,
'返回openpy.read\u py\u url(utarget,skip\u encoding\u cookie=skip\u encoding\u cookie)\n',
'除UnicodeDecodeError:\n',
'如果不是仅py\u:\n',
'从urllib导入urlopen#延迟导入\n',
'response=urlopen(目标)\n',
“返回response.read().decode('latin1')\n”,
'提升值错误(“\'%s\'似乎不存在”]

KABOOM!有人解释一下吗?顺便说一句,我使用Python2.7和Enthow Canopy。

当你打开一个带有
'r+'
的文件时,它不会被截断,它仍然保留它的旧内容。要将它截断为0字节,请在打开它之后立即调用
fic.truncate(0)

必须在同一文件对象的读写操作之间进行搜索(否则,由于缓冲,结果未定义),例如添加
fic。seek(0,0)
(或任何其他搜索)af