2012-10-01 32 views
-2

我想從多個文本(nmap)文檔中收集特定的行,然後用表格格式創建一個新的文件。我還沒有進入表格部分,因爲我無法獲得追加工作。Python 2.7.2。如何將多個文件中的特定行添加到一個文件中。

#imports 
import os 

#Change directories 
os.chdir ("M:\\Daily Testing") 

#User Input 
print "What is the name of the system being scanned?" 
sys = raw_input("> ") 

#Subfolder selected 
os.chdir (sys) 
os.chdir ("RESULTS") 

#variables 
tag = ["/tcp", "/udp"] 
fout = [sys + " Weekly Summary.csv"] 

import glob 
for filename in glob.glob("*.nmap"): 
    with open(filename, "rU") as f: 
     for line in f: 
      if not line.strip(): 
       continue 
      for t in tag: 
       if t in line: 
        fout.write(line) 
       else: 
        continue 
+1

請更具體。你遇到了什麼錯誤? –

+1

東西似乎與'fout'是一個列表,然後調用'fout.write()'。 –

+0

我得到(目前)的錯誤是「AttributeError的:‘名單’對象有沒有屬性‘寫’」在fout.write線 – user1197368

回答

3

你忽視打開一個文件追加到(fout是一個列表,而不是一個文件對象,因此它沒有.write()法)。

改變線

fout = [sys + " Weekly Summary.csv"] 

with open(sys+" Weekly Summary.csv", "w") as fout: 

,並相應地縮進以下行。

所以,這樣的事情:

<snip> 
import glob 
with open(sys + " Weekly Summary.csv", "w") as fout: 
    for filename in glob.glob("*.nmap"): 
     with open(filename, "rU") as f: 
      for line in f: 
       if not line.strip(): 
        continue 
       for t in tag: 
        if t in line: 
         fout.write(line) 
        else: 
         continue 
+0

這樣做。萬分感謝! – user1197368

相關問題