2014-05-08 71 views
0

我有有一些標題行和某些列(數字)的文本文件。 我想讀這個文件跳過標題,然後選擇一些列 使用Python腳本在一個新的文件寫入它們。的Python:讀寫文本文件頭和數字列

例如,讓我們稱之爲下面in_table.txt的數據。 我想跳過頭(也空行), 然後選擇第一和第四列(僅數值) 和他們在一個新的文件保存out_table.txt沒有頭,只是數字。 我該如何使用Python腳本來做到這一點?

非常感謝!

in_table.txt:

hline1 hline1 hline1 
hline2 hline2 hline2 

hline3 hline3 hline3 

par1 par2 par3 par4 par5 
1. 10. 100. 1000. 10000. 
2. 20. 200. 2000. 20000. 
3. 30. 300. 3000. 30000. 
4. 40. 400. 4000. 40000. 
5. 50. 500. 5000. 50000. 

回答

2

如果你有空間的分隔符堅持使用

with open('in_table.txt') as f: 
    # Iterate through the file until the table starts 
    for line in f: 
     if line.startswith('------'): 
      break 
    # Read the rest of the data, using spaces to split. 
    data = [r.split() for r in f] 

with open('out_file.csv', 'w') as of: 
    for r in data: 
     # Write only column 0 and 2 (re: 0-indexing) 
     of.write('%s, %s\n'%(r[0], r[2])) 

CSV

如果用逗號分隔你很可能蟒蛇內置csv

import csv 
with open('in_table.txt') as f: 
    for line in f: 
     if line.startswith('------'): 
      break 
    data = [r for r in csv.reader(f)] 

with open('out_file.csv', 'w') as of: 
    for r in data: 
     of.write('%s, %s\n'%(r[0], r[2])) 

或者更簡潔

import csv 
with open('in_table.txt') as f: 
    for line in f: 
     if line.startswith('------'): 
      break 
    data = [r[0]+r[2] for r in csv.reader(f)] 

wrt = csv.writer(open('out_file.csv', 'w')) 
wrt.writerows(data)