我在想要读取第三列的文件中有以下行;在文件中,我没有数字列:Python:通过一个文件循环访问特定行
- 红色;蓝色;绿色;白色;橙子;
- 绿色;白色;橙子;
- 蓝色;绿色;白色;
- 红色;蓝色;绿色;白色;
- 蓝色;绿色;白色;橙子;
- 橙色
- 绿色;白色;橙子;
- 白色;橙色
- 绿色;
我用这个代码行做到这一点:
lines = i.split(";")[2]
的问题是,某些行只有一个列或两个,所以它给了我“索引超出范围”的错误。请告诉我如何解决这个问题?
非常感谢 阿迪亚
我在想要读取第三列的文件中有以下行;在文件中,我没有数字列:Python:通过一个文件循环访问特定行
我用这个代码行做到这一点:
lines = i.split(";")[2]
的问题是,某些行只有一个列或两个,所以它给了我“索引超出范围”的错误。请告诉我如何解决这个问题?
非常感谢 阿迪亚
使用片而不是指数。
>>> with open('test.txt') as f_in:
... column3 = (line.split(';')[2:3] for line in f_in)
... column3 = [item[0] for item in column3 if item]
...
>>> column3
[' Green', ' Orange', ' White', ' Green', ' White', ' Orange']
+1:脑海中有着几乎相同的想法。 – eldarerathis 2010-10-08 14:10:20
怎么样这样的:
cols = i.split(";")
if (len(cols) >= 3):
lines = cols[2]
else:
#whatever you want here
简单的解决方案是检查列数并忽略少于三列的行。
third_columns = []
with open("...") as infile:
for line in infile:
columns = line.split(';')
if len(columns) >= 3:
third_columns.append(columns[2])
如果你解析CSV(好像你这样做),你最好使用大量的现存的CSV解析器之一,e.g. the one in the standard library。
for line in open("file"):
try:
s=line.split(";")[2]
except: pass
else:
print s
裸露的除外是邪恶的 – SilentGhost 2010-10-08 15:01:28
好吧,当没有足够的列时想做什么? – SilentGhost 2010-10-08 14:07:10