2015-01-29 9 views
-1

간단한 문제가 있습니다. 프로그램에서 - 프로그램은 중요하지 않습니다 - 첫 번째 줄만, 저는 empty.txt라는 빈 파일을 엽니 다. 그렇다면 함수를 정의하지만 main에서는 사용하지 마십시오 ... 그래서 실제로 아무 것도 쓰지 않습니다.Python 2.7 : 전체 코드가 파일 문제로 작성되는 경우

이 거의 전체 코드 : 그런 다음

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'] 

카복! 아무도 설명이 없나요? 그건 그렇고, 나는 Enthought Canopy와 함께 Python 2.7을 사용합니다.

+0

사람들을 도와 줄 기회를 늘리려면 코드와 출력을 게시하십시오. –

+0

나는 당신의 행동을 재현 할 수 없었다. 명령 프롬프트에서 ** C : \ Users \ Julien \ Desktop \ PS BOT **로 cd하고'type empty.txt '명령을 실행하십시오. 너 뭐가 보이니? –

+0

@HaiVu 어떻게 전체 코드를 게시 할 수 있습니까? 사이트의 모든 특수 명령 또는 모든 단일 행을 가져 와서 4 공백을 추가합니까? 그래서 긴 코드 페이지에 pastebin을 사용합니다. –

답변

0

'r+'으로 파일을 열면 잘리지 않으며 여전히 이전 내용을 유지합니다. 0 바이트로 자르려면 바로 열기 후 fic.truncate(0)으로 전화하십시오.

동일한 파일 객체에 대해 읽기 및 쓰기 작업을 수행해야합니다 (그렇지 않으면 결과가 버퍼링으로 인해 정의되지 않습니다). write 호출 후 fic.seek(0, 0) (또는 다른 검색)을 추가하십시오.

+0

empty.txt가 열리기 전에 비어있었습니다. 나는 당신의 대답을 이해하지 못합니다. 나는 코드를 열려고 할 때 코드를 자르려고하고 싶지 않다. –