2009-10-29 2 views
0

을 부여하고 벽에 붙어있어삽입 문자열은 내가 문제가 일하고 파일 객체

나는 텍스트 파일의 (잠재적으로 큰) 세트가, 나는 순서를 적용해야 필터 및 변환을 가져 와서 다른 위치로 내 보냅니다.

그래서 대략
def apply_filter_transformer(basepath = None, newpath = None, fts= None): 
    #because all the raw studies in basepath should not be modified, so I first cp all to newpath 
    for i in listdir(basepath): 
     file(path.join(newpath, i), "wb").writelines(file(path.join(basepath, i)).readlines()) 
    for i in listdir(newpath): 
     fileobj = open(path.join(newpath, i), "r+") 
     for fcn in fts: 
      fileobj = fcn(fileobj) 
     if fileobj is not None: 
      fileobj.writelines(fileobj.readlines()) 
     try: 
      fileobj.close() 
     except: 
      print i, "at", fcn 
      pass 
def main(): 
    apply_filter_transformer(path.join(pardir, pardir, "studies"), 
         path.abspath(path.join(pardir, pardir, "filtered_studies")), 
         [ 
         #transformer_addMemo, 
          filter_executable, 
          transformer_identity, 
          filter_identity, 
          ]) 

을 가지고 apply_filter_transformer에서 FTS는 파이썬 파일 객체를 받아 파이썬 파일 객체를 반환 기능의 목록입니다. 내가 들어간 문제는 문자열을 텍스트 객체에 삽입하려고 할 때 정보가없는 오류가 발생하고 아침 내내 막혔다는 것입니다.

def transformer_addMemo(fileobj): 
    STYLUSMEMO =r"""hellow world""" 
    study = fileobj.read() 
    location = re.search(r"</BasicOptions>", study) 
    print fileobj.name 
    print fileobj.mode 
    fileobj.seek(0) 
    fileobj.write(study[:location.end()] + STYLUSMEMO + study[location.end():]) 
    return fileobj 

누군가가 나에게 오류에 대한 자세한 정보를 줄 수 있다면이 나에게

Traceback (most recent call last): 
File "E:\mypy\reg_test\src\preprocessor\preprocessor.py", line 292, in <module> 
    main() 
File "E:\mypy\reg_test\src\preprocessor\preprocessor.py", line 288, in main 
filter_identity, 
File "E:\mypy\reg_test\src\preprocessor\preprocessor.py", line 276, in  apply_filter_transformer 
    fileobj.writelines(fileobj.readlines()) 
    IOError: [Errno 0] Error 

을 제공합니다, 나는 매우 매우 감사하겠습니다.

+0

서식을 수정하십시오. –

답변

1

게시 한 코드의 오류의 원인을 알 수 없습니다. 문제는 변환 함수에 대해 채택한 프로토콜에있을 수 있습니다.

내가 코드를 조금 단순화 수 있습니다 :

나는 fcn 내 원본 파일이었다 모드에서 열려있는 파일을 반환해야합니까 어떤 보증
fileobj = file.open(path, mode) 
fileobj = fcn(fileobj) 
fileobj.writelines(fileobj.readlines()) 

? 그것은 열려있는 파일을 반환합니다. 그것은 파일을 반환합니까? 글쎄, 나는하지 않는다.

프로세스에서 파일 개체를 사용하는 데 아무 이유가없는 것처럼 보입니다. 전체 파일을 메모리로 읽으므로 변환 함수가 문자열을 반환하고 반환하지 않는 이유는 무엇입니까? 그래서 코드는 다음과 같습니다 무엇보다도

with open(filename, "r") as f: 
    s = f.read() 
for transform_function in transforms: 
    s = transform_function(s) 
with open(filename, "w") as f: 
    f.write(s) 

를 하나의 문제는 다른 영향을 미치지 않도록이 완전히 파일 데이터-변환 부분에서 프로그램의 I/O 부분을 분리한다.

1

modifing에 또는 파일 그룹 읽기에 편리 파이썬 모듈이있다 : fileinput

나는이 오류의 원인이 무엇인지 확실하지 않다가. 그러나 전체 파일을 메모리로 읽어들이는 것은 파일이 잠재적으로 크기 때문에 나쁜 생각입니다. fileinput을 사용하면 파일을 쉽게 바꿀 수 있습니다. 예 :

import fileinput 
import sys 

for line in fileinput.input(list_of_files, inplace=True): 
    sys.stdout.write(line) 
    if keyword in line: 
     sys.stdout.write(my_text) 
관련 문제