2009-10-29 43 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是功能列表,接受一個Python文件對象,並返回一個Python文件對象。我遇到的問題是,當我想將字符串插入到文本對象中時,我得到了無意義的錯誤,並且一整個早晨都陷入了僵局。

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

請修復您的格式。 – 2009-10-29 17:53:02

回答

1

從您發佈的代碼中判斷錯誤並非真的可行。問題可能在於您爲轉換功能採用的協議。

我會簡化代碼位:

fileobj = file.open(path, mode) 
fileobj = fcn(fileobj) 
fileobj.writelines(fileobj.readlines()) 

我有什麼保證fcn返回一個文件,該文件在我原來的文件是模式打開?它返回一個根本打開的文件?它返回一個文件?那麼,我不知道。

它似乎沒有任何理由讓你甚至在你的過程中使用文件對象。既然你正在將整個文件讀入內存,爲什麼不直接讓你的轉換函數接受並返回字符串呢?所以,你的代碼應該是這樣的:

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

沒有爲對矯正或閱讀一組文件得心應手Python模塊: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) 
相關問題