2016-08-09 10 views
0

私はヘルプを探しています。このように見える.txtファイルのcentosサーバーからのマルチパス出力があります。.txtファイルを読み込んで選択データを.csvにエクスポートします

asm (393040300403de) dm-12 HITACHI 
size=35G queue_if_no_path 
    |- 1:0:0:18 sda 65:48 active ready running 
    `- 3:0:0:18 sdbc 70:368 active ready running 
3600300300a4c dm-120 HITACHI 
size=50G queue_if_no_path 
    |- 1:0:0:98 sdc 70:48 active ready running 
    `- 3:0:0:98 sdca 131:368 active ready running 

.csvファイルにエクスポートすると、次のようになります。

DISKS_NAME LUN    LUNID DM-NAME SIZE MULTPATH 
asm  393040300403de 03de dm-12 35G sda sdbc 
No_device 3600300300a4c 0a4c dm-120 50G sdc sdca 

これは限り私が得ているが、これは単に、すべての行を読み込み、別の列にするたびにそれを置く、それはあなたが唯一のエントリの2種類を持っていると仮定すると、スペース

import csv 

readfile = 'multipath.txt' 
writefile = 'data.csv' 
with open(readfile,'r') as a, open(writefile, 'w') as b: 
    o=csv.writer(b) 
    for line in a: 
     o.writerow(line.split()) 
+0

あなたのコードとデータをそれぞれコードブロックに入れて、読みやすくしてください。 – janbrohl

+0

あなたの入力ファイルは非常に書きやすいあなた自身のパーサであれば、各行を読むのと同じくらい単純ではありません。あなたは[regex](https://docs.python.org/2/library/re.html)のようなものを使って、それぞれ4行のブロックを解析するか、手動で行ごとに分割し、テキストの既知のインデックスに従って構文解析します。 –

+0

csvファイルとtxtファイルのフォーマット方法について詳しく説明してください。ありがとうございました。 –

答えて

0

を見つけました上のサンプルで説明したように、各行は、その中の要素の数の要素として、line.split()で区切って定義できます。たとえば:もちろん

disk_name = "" 
... # other parameters you need to keep track of across lines. I'd suggest creating a class for each lun/disk_name. 

for line in a: 
    line_data = line.split() 

    if len(line_data) == 4: 
     # this will match and 'asm (393040300403de) dm-12 HITACHI' 
     disk_name, lun, dm_name, _ = line_data 
     # process these variables accordingly (instantiate a new class member) 
     continue # to read the next line 

    else if len(line_data) == 3: 
     # this will match '3600300300a4c dm-120 HITACHI' 
     lun, dm_name, _ = line_data 
     disk_name = "No_device" 
     # process these variables accordingly 
     continue 

    if len(line_data) == 2: 
     # this will match 'size=35G queue_if_no_path' 
     size, _ = line_data 
     # process the size accordingly, associate with the disk_name from earlier 
     continue 

    if len(line_data) == 7: 
     # this will match '|- 1:0:0:18 sda 65:48 active ready running' etc. 
     _, _, path, _, _, _, _ = line_data 
     # process the path accordingly, associate with the disk_name from earlier 
     continue 

は、ラインはあなたが必要とするデータの種類ではなく、アイテムのちょうど右の数が含まれている場合に動作するように正規表現を使用して、より柔軟になります。しかし、これはあなたを開始する必要があります。

この順番で行を処理すると、常に新しいdisk_name/lunが選択され、そのディスクに次の「データ」行が割り当てられます。新しいディスクをヒットすると、それに続く行が新しいディスクなどに関連付けられます。

+0

ありがとうございます。私はこれを試す必要があります – sharath

関連する問題