2010-10-08 87 views
1

我在想要读取第三列的文件中有以下行;在文件中,我没有数字列:Python:通过一个文件循环访问特定行

  1. 红色;蓝色;绿色;白色;橙子;
  2. 绿色;白色;橙子;
  3. 蓝色;绿色;白色;
  4. 红色;蓝色;绿色;白色;
  5. 蓝色;绿色;白色;橙子;
  6. 橙色
  7. 绿色;白色;橙子;
  8. 白色;橙色
  9. 绿色;

我用这个代码行做到这一点:

lines = i.split(";")[2] 

的问题是,某些行只有一个列或两个,所以它给了我“索引超出范围”的错误。请告诉我如何解决这个问题?

非常感谢 阿迪亚

+0

好吧,当没有足够的列时想做什么? – SilentGhost 2010-10-08 14:07:10

回答

1

使用片而不是指数。

>>> 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'] 
+0

+1:脑海中有着几乎相同的想法。 – eldarerathis 2010-10-08 14:10:20

2

怎么样这样的:

cols = i.split(";") 
if (len(cols) >= 3): 
    lines = cols[2] 
else: 
    #whatever you want here 
2

简单的解决方案是检查列数并忽略少于三列的行。

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

0
for line in open("file"): 
    try: 
     s=line.split(";")[2] 
    except: pass 
    else: 
     print s 
+2

裸露的除外是邪恶的 – SilentGhost 2010-10-08 15:01:28