2012-12-14 189 views
2

我必須刪除許多文件的前2個標題並將其替換爲另一個。由於我是Python和編程新手,我一直在使用下面的代碼:刪除標題並添加另一個

import glob 
import os 
list_of_files = glob.glob('./*.txt') 
for file_name in list_of_files: 
    os.system('sed "1,2d" %s | sort -k1 > %s.sort' %(file_name,file_name)) 
    os.system ('cat header file %s.sort > %s.header' %(file_name,file_name)) 

它的工作原理。不過,我認爲應該有更好的方法來完成這件事。此外,我不必要地製作一個額外的文件* .sort,我不需要。

+0

至少,您可以使用-i標誌在位。 – Anov

+0

@Anov ......這會讓你失去原始文件。 – glglgl

+1

@glglgl你可以發送擴展標誌而不是'',它會創建一個備份。正如OP所說,他「不必要地增加了一個fil * .sort」,我認爲他不需要保留原文。 – Anov

回答

3

信不信由你,你可以在純Python做到這一點很容易地:

import itertools 
with open(filename) as fin: 
    ilines = itertools.islice(fin, 2, None) #this throws away the first 2 lines 
    lines = sorted(ilines, key=lambda x: x.split()[0]) #sort lexicographically on first column 

with open('header') as header, open('%s.header'%filename) as fout: 
    fout.writelines(header) #write the header 
    fout.writelines(lines) #write the data 

大功告成。稍微延長午休時間,因爲python可以幫助您節省時間* :-)。

*(或者,花一些你長的午餐學習更多的很酷的事情蟒蛇來!)

編碼快樂!

+0

@glglgl - 你今天只是編輯我所有的答案,是不是;-) – mgilson

+0

只有當有東西需要編輯時:-) – glglgl

+0

@glglgl - 我確定你是否回頭看過我的老答案,你會發現足夠讓自己一個複製編輯徽章:p – mgilson

1

避免os.system

第一種方法可能是

import glob 
import subprocess 
list_of_files = glob.glob('./*.txt') 
for file_name in list_of_files: 
    sp1 = subprocess.Popen(['sed', '1,2d', file_name], stdout=subprocess.PIPE) 
    sp2 = subprocess.Popen(['sort', '-k1'], stdin=sp1.stdout, stdout=subprocess.PIPE) 
    out = open(file_name + '.header', 'w') 
    sp3 = subprocess.Popen(['cat', 'header', 'file', '-'], stdin=sp2.stdout, stdout=out) 
    sp1.stdout.close() # sp2 got it, not our business any longer 
    sp2.stdout.close() # sp3 got it, not our business any longer 
    out.close() 
    sp1.wait() 
    sp2.wait() 
    sp3.wait() 
+0

......就像第一種方法。 [mgilson的解決方案](http://stackoverflow.com/a/13882120/296974)是更好的,因爲它是所有的東西本地而不是調用其他程序。 – glglgl

相關問題