2013-02-16 99 views
0
import os 
from os.path import splitext,basename 
import sys 
from lxml import etree 

#clean out old files 
def cleanBrds(args, dirname,files): 
    print "checking "+dirname 
    for file in files: 
     if file.endswith("_pyclean.brd"): 
      if os.path.exists(file): 
       print "removing "+file 
       os.remove(file) 

#prep files 
def sanBrds(args, dirname,files): 
    print "checking "+dirname 
    for file in files: 
     if file.endswith(".brd"): 
      print "found "+file 
      newfile = splitext(basename(file))[0]+"_pyclean.brd" 
      tree=etree.parse(file) 
      for elem in tree.xpath('//signal'): 
       elem.getparent().remove(elem) 
      f=open(newfile,'w') 
      f.write(etree.tostring(tree)) 
      f.close(); 

base_dir="." 
os.path.walk(base_dir,cleanBrds,None) 
os.path.walk(base_dir,sanBrds,None) 
# python prepbrd.py 
checking . 
checking ./naut 
checking . 
found erct.brd 
checking ./naut 
found nautctrl.brd 
Traceback (most recent call last): 
    File "prepbrd.py", line 43, in <module> 
    os.path.walk(base_dir,sanBrds,None) 
    File "/usr/lib/python2.6/posixpath.py", line 236, in walk 
    walk(name, func, arg) 
    File "/usr/lib/python2.6/posixpath.py", line 228, in walk 
    func(arg, top, names) 
    File "prepbrd.py", line 22, in sanBrds 
    tree=etree.parse(file) 
    File "lxml.etree.pyx", line 2706, in lxml.etree.parse (src/lxml/lxml.etree.c:49958) 
    File "parser.pxi", line 1500, in lxml.etree._parseDocument (src/lxml/lxml.etree.c:71797) 
    File "parser.pxi", line 1529, in lxml.etree._parseDocumentFromURL (src/lxml/lxml.etree.c:72080) 
    File "parser.pxi", line 1429, in lxml.etree._parseDocFromFile (src/lxml/lxml.etree.c:71175) 
    File "parser.pxi", line 975, in lxml.etree._BaseParser._parseDocFromFile (src/lxml/lxml.etree.c:68173) 
    File "parser.pxi", line 539, in lxml.etree._ParserContext._handleParseResultDoc 

(src/lxml/lxml.etree.c:64257) File "parser.pxi", line 625, in lxml.etree._handleParseResult (src/lxml/lxml.etree.c:65178) File "parser.pxi", line 563, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:64493) IOError: Error reading file 'nautctrl.brd': failed to load external entity "nautctrl.brd"蟒蛇os.path.walk無法打開文件

我是相當新的這一點,但似乎我可能不會從os.path.walk正確地傳遞參數給其它功能。我想首先刪除以_pyclean.brd結尾的所有文件,然後對剩餘的.brd文件(它們是xml)進行操作。這些函數在一個平面目錄中工作正常,但遞歸地得到上述錯誤。

回答

3

files中的文件名是短名稱。你想使用你可以使用的全路徑os.path.join

def sanBrds(args, dirname, files): 
    print "checking ", dirname 
    for file in files: 
     fullpath = os.path.join(dirname, file) 
     if fullpath.endswith(".brd"): 
      print "found ", file 
      newfile = splitext(basename(fullpath))[0] + "_pyclean.brd" 
      tree = etree.parse(fullpath) 
      # ... 
+0

謝謝。 os.path.join做了訣竅。 – johnn 2013-02-16 23:57:40