首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

list index out of range 求解解决办法

2012-06-19 
list index out of range 求解import os,re,linecachedef fun(path):for root,dirs,files in os.walk(path

list index out of range 求解
import os,re,linecache
def fun(path):
  for root,dirs,files in os.walk(path):
  for fn in files:
  rootpath = os.path.join(root,fn)
  filetype=fn.split('.')[1]
  if filetype in['xml']:
  print(rootpath)  
  new=(linecache.getline(rootpath,4)).rstrip()
  print (new)
  #print (type(new))
  newsp=new.split('.')
  #print (type(newsp))
  print(newsp[1])
  f= open(rootpath,'r+')
  d=f.read()
  open(rootpath, 'w').write(re.sub(r'a', 'b', d))
  f.close()
  else:
  continue
fun(r'C:\wmpub')



C:\wmpub\a.xml

Traceback (most recent call last):
  File "C:\Documents and Settings\Administrator\桌面\test.py", line 21, in <module>
  fun(r'C:\wmpub')
  File "C:\Documents and Settings\Administrator\桌面\test.py", line 14, in fun
  print(newsp[1])
IndexError: list index out of range
>>>

[解决办法]
print(newsp[1])这里,newsp要么是个空list[],要么长度是1,没有[1],只有[0]
建议你print之前做个判断

if len(newsp)>1:
print(newsp[1])
else:
print(newsp)
[解决办法]
意思是你访问的东西已经超出了数组的界限
[解决办法]

Python code
#!/usr/bin/pythonimport os,re,linecachedef walkFilesInPath(path, extfilter='.xml'):    for root, dirs, files in os.walk(path):        for filename in files:            if os.path.splitext(filename)[1] == extfilter:                yield os.path.join(root, filename)def processFile(filename):    newsp = (linecache.getline(filename,4)).rstrip().split('.')    print(newsp)def fun(path):    for filename in walkFilesInPath(path, extfilter='.xml'):        processFile(filename)fun(r'C:\wmpub') 

热点排行