删除表头并添加另一个

2024-04-25 09:34:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须删除许多文件的头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,我不需要。在


Tags: 文件of代码nameimportos编程files
2条回答

信不信由你,你可以很容易地用纯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可以帮助您节省时间*:-)。在

*(或者,花点时间在午餐上学习python提供的更多酷的东西!)在

编码快乐!在

避免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()

相关问题 更多 >