list index out of range 求解

chen_jia_xing 2012-06-14 12:20:40
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
>>>
...全文
220 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
chen_jia_xing 2012-06-14
  • 打赏
  • 举报
回复
没有越界啊 print (new) 这个是文件里的第四行,不要后面的代码打印出来是一个list,里面是有值的,4个以上
bugs2k 2012-06-14
  • 打赏
  • 举报
回复
意思是你访问的东西已经超出了数组的界限
tim_spac_126 2012-06-14
  • 打赏
  • 举报
回复

#!/usr/bin/python

import os,re,linecache

def 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')
这样子输出了啥?
libralibra 2012-06-14
  • 打赏
  • 举报
回复
print(newsp[1])这里,newsp要么是个空list[],要么长度是1,没有[1],只有[0]
建议你print之前做个判断

if len(newsp)>1:
print(newsp[1])
else:
print(newsp)

37,721

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧