2016-02-19 61 views
0

下面的代碼可以工作,但將多行字符串的每個換行符分配給新行,而不是一個單元格的所需狀態。將多行字符串輸出到單個csv.writer行中的Python問題

雖然研究可能的解決方案,我讀:

  • 我應該嘗試在雙引號將字符串
  • carriage return更換newline通過[]聲明
  • 幫助
  • 解析爲一個列表/元組

經過上述嘗試,我完全困惑,爲什麼這不起作用。如果我刪除newline它將一切分配給行中的單個單元格,但很難閱讀。

輸出字符串csv.writer時沒有辦法保存格式嗎?

def run_rip(): 
os.chdir('/REGRIPPERDIR/RegRipper2.8') 
for k in ntDict: 
    run_command = "".join(["./rip.pl", " -r /APATH/NTUSER.DAT -p ", str(k)]) 
    process = subprocess.Popen(run_command, 
           shell=True, 
           stdout=subprocess.PIPE, 
           stderr=subprocess.PIPE) 
    out, err = process.communicate() 
    pattern = re.compile('lastwrite|(\d{2}:\d{2}:\d{2})|alert|trust|Value') 
    grouping = re.compile('(?P<first>.+?)(\n)(?P<second>.+?)([\n]{2})(?P<rest>.+[\n])', re.MULTILINE | re.DOTALL) 
    if pattern.findall(out): 
     match = re.search(grouping, out) 
     first = match.group('first') 
     second =match.group('second') 
     rest = ('"%s' % os.linesep.join([s for s in match.group('rest').splitlines() if s])) 
     rest = rest.replace('\n','\r\n') 
     headers = ['Name', 'Description', 'Found'] 
     f = csv.writer(open('/APATH/ntuser.csv', 'ab'), 
         dialect=csv.excel, 
         delimiter='\t') 
     f.writerow(headers) 
     f.writerow((first, second, rest)) 
     print(out) 
    ntDict.popitem(last=False) 

run_rip() 

樣本輸出: Three Column Output

/編輯:我被要求在下面的意見,因爲它被收集後第三個字符串rest的樣本。以下文字將傳遞給csv.writer

Baseline\n #First string as defined by the regex 
(All) scans a hive\n #Second String as defined by the regex 

Total values checked : 64\n #This and below is the rest string 
Number of binary value lengths : 11\n 
...\n 
Value -5: 176 bytes [# times: 1]\n 
Value -4: 712 bytes [# times: 5]\n 

期望狀態: enter image description here

+0

我可以建議你發佈一些csv文本(即一個字符串),給你所需的佈局?根本問題在於csv並不是一個真正的標準。你問的東西看起來是關於產生粘貼圖像的應用程序接受的格式。 –

+0

@dementedhedgehog我與之交互的應用程序是Registry Ripper,它輸出非標準文本並創建不需要的過多結果的分配。所以我的方法是調用應用程序,讀取stdout,將數據分爲三個變量,如上所述,然後輸出到.csv。然而,第三個變量有許多換行符,不幸的是它們正在被csv.writer讀取並輸出到不同的單元格,如'sample output'中所示。有沒有辦法將輸出中的換行/回車保留爲.csv,以便我可以獲得'期望的狀態'? – ImNotLeet

+0

有沒有其他的.csv模塊可以完成上述操作?我的問題不清楚,是否缺少賞金?自從我發佈以來,上述問題一直困擾着我。我已經嘗試了多個小時的解決方案,並且它只是在我的掌握之外(可能是因爲我是編程新手)。 – ImNotLeet

回答

0

在評論的指導下,我找到了我的答案。只需excel即可格式化(因爲評論中包含的原因)。但是,在LibreOffice中打開時,格式將保留。

評論中的建議線程(Importing CSV with line breaks in Excel 2007)有一個特定的解決方法,其中包括引用實際換行符與引用整個字符串,這正是我所做的。

2

不是一個答案......但我想代碼格式化。

import csv 
x = ("1", "2\n3", "4") 
f = csv.writer(open('foo', 'w'), 
        dialect=csv.excel, 
        delimiter='\t') 
f.writerow(x) 

產生以下:

$ less foo 
1  "2 
3"  4 

這就是 「有效」 製表符分隔CSV ..它只是Excel不處理它 「正常」。因爲它不是一個標準化的格式,引用中的東西實際上是更多的實現問題。 23號左右的額外雙引號是令人討厭的。

檢出https://pypi.python.org/pypi/xlwt(前xml excel格式)或http://xlsxwriter.readthedocs.org/(xml excel格式),用於第三方庫直接編寫excel。