索引错误:列表索引超出范围?
我遇到一个问题,需要大家的帮助。
我读取了一个大小为100MB的rar文件,并处理了里面的文本文件。
import glob
import os
import UnRAR2
from os import path, access, R_OK
os.chdir("E:\\sms")
for file in glob.glob("*.rar"):
# extract test.txt to memory
entries = UnRAR2.RarFile(file).read_files('*.txt')
test_content = entries[0][1]
#print test_content
for line in test_content.split("\n"):
A=line.split(' ')
print A[1]
结果:
19009057
7030
9119
9119
....
....
bla...bla...
......
9119
9119
9119
7050
9119
Traceback (most recent call last):
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "E:\LAPTRINH\Android\adt-bundle-windows\eclipse\plugins\org.python.pydev_2.7.1.2012100913\pysrc\pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "C:\Users\The\Documents\workspace\unrar\test_unrar.py", line 13, in <module>
print A[1]
IndexError: list index out of range
请大家帮帮我!
谢谢大家!!!
3 个回答
0
这个错误的意思是,line
被分割成了 A
,但是它没有第二个项目,这就说明没有其他内容可以解析了,也就是说你已经到达了文件的末尾。
0
如果你文件的最后一行是 \n
,那么 A[1]
可能会有问题。你需要重新考虑一下你获取信息的方式。
0
你的一行代码(可能是最后一行)格式不符合你的预期。在你的内部循环中,做以下操作:
A=line.split(' ')
if len(A) > 1:
print A[1]