2014-04-16 48 views
0

這是我的腳本。它目前發現路徑中的所有文件其中包含* 週期 * .log然後找到那些包含「timeout」的文件中的所有行,並將它們過濾爲outfilecamera以及文件的名稱它發現它。如何搜索文件,計算點擊次數並將數字寫入.csv中的B列?

i = 0 

ii = "\n" 

for i in range(0,listlength): 
    path = pathlist[i].strip() 
    outfilecamera = join((path), 'cameratimeouts.txt') 
    os.chdir(path) 
    for path in glob.glob("*cycle*.log"): 
     with open(path) as f_in, open(outfilecamera, 'a') as f_out: 
      f_out.writelines(path) 
      f_out.writelines(ii) 
      f_out.writelines(line for line in f_in if "timeout of" in line) 

我想要做的一樣好是計數的命中在文件中找到的次數和數量粘貼到B列在CSV文件中。即每行將是每個文件中的命中數。列A理想地等於i

我一直在尋找年齡和如何找到一個計數功能!?

我很感謝我們的幫助!

回答

1

的次數其發現的是隱藏在這裏:

f_out.writelines(line for line in f_in if "timeout of" in line) 

所以,你所要做的就是先消費發電機,說成一個列表:

matched_lines = list(line for line in f_in if "timeout of" in line) 
f_out.writelines(matched_lines) 

下,簡單地收集數量匹配每個文件。在你的循環頂部創建空白列表,然後你的循環中,添加文件名和計數它:

file_counts = [] 

# .. your loop starts 

    matched_lines = list(line for line in f_in if "timeout of" in line) 
    f_out.writelines(matched_lines) 
    file_counts.append((os.path.basename(path),len(matched_lines))) 

一旦你處理完文件:

with open('results.csv','w') as f: 
    writer = csv.writer(f, delimiter=",") 
    writer.writerow(['File Name','Count']) 
    writer.writerows(file_counts) 
0

下面是你需要......

import csv 
import glob 

searched = 'timeout of' 
with open('output.csv', 'wb') as csvfile: 
    cwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) 
    cwriter.writerow(['File', 'Number']) 
    for path in glob.glob("*cycle*.log"): 
     with open(path) as f_in: 
      n = 0 
      for line in f_in.readlines(): 
       if searched in line: 
        n += 1 
      cwriter.writerow([path, n]) 
0

什麼grep的?這項任務將非常簡單。

grep -c 'timeout of' *cycle*.log 

對於像輸出CSV,則需要更換結腸逗號:

grep -c 'timeout of' *cycle*.log | sed 's/:/,/' 

並把結果到cameratimeouts.txt文件:

grep -c 'timeout of' *cycle*.log | sed 's/:/,/' >cameratimeouts.txt 

如果你會堅持與python,我的解決方案將是:

for i in range(0,listlength): 
    path = pathlist[i].strip() 
    outfilecamera = join((path), 'cameratimeouts.txt') 
    os.chdir(path) 
    for path in glob.glob("*cycle*.log"): 
     with open(path) as f_in, open(outfilecamera, 'a') as f_out: 
      f_out.write('%s,%d\n' % (path, sum(l.count('timeout of') for l in f_in))) 
相關問題