簡體   English   中英

Python:在文件中循環查找特定行

[英]Python: loop through a file for specific lines

我要在第三列中的文件中有以下幾行: 在文件中,我沒有數字列:

  1. 紅色; 藍色; 綠色; 白色; 橙子;
  2. 綠色; 白色; 橙子;
  3. 藍色; 綠色; 白色;
  4. 紅色; 藍色; 綠色; 白色;
  5. 藍色; 綠色; 白色; 橙子;
  6. 橙子
  7. 綠色; 白色; 橙子;
  8. 白色; 橙子
  9. 綠色;

我使用以下代碼行來做到這一點:

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

問題是某些行只有一兩列,所以它給我“索引超出范圍”錯誤。 請告訴我如何解決這個問題?

非常感謝Adia

那這樣的事情呢:

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解析器之一, 例如,標准庫中的之一

使用切片而不是索引。

>>> 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']
for line in open("file"):
    try:
        s=line.split(";")[2]
    except: pass
    else:
        print s

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM