从文本文件中的列表中删除特定元素

时间:2014-09-15 15:46:53

标签: python

我有一个1825 x 51表的文本文件。我试图读取文本文件并将此表写入新的文本文件,同时从表中删除某些列。我无法弄清楚如何删除整列,因为列表是一个字符串,所以我试图进入每一行并使用if / else语句来确定元素是否在所需的范围内。如果是,请将其写入输出,否则将其删除。

 if i in range(1,3)+[14]+range(20,27)+range(33,38)+[43]+[45]:
     newNum=data[i]
     data[i]=newNum
 else:
     delete.data

这是我第一次使用python,所以非常感谢任何帮助!

来自评论的

代码

with open(inputfilepath,'r') as f:
    outputfile=open(outputfilepath,'w+')
    inSection=False
    for line in f:
        if begin in line:inSection=True
        if inSection:
            keep=range(1,3)+[14]+range(20,27)+range(33,38)+[43]+[45]
            tmp=[]
            spl=line.split('  ')
            for idx in keep:
                tmp.extend(spl[idx])
            outputfile.write('%s\n' % '  '.join(tmp))            
        if end in line:inSection=False

2 个答案:

答案 0 :(得分:0)

keep = [1,2,3,14,20,21,22,23,24,25,26,27,33,34,35,36,37,38,43,45]
with open('textfile') as fin, open('textout') as fout:
   for ln in fin:
       tmp = []
       spl = ln.split(' ')
       for idx in keep:
           tmp.append(spl[idx])
       fout.write('%s\n' % ' '.join(tmp))

答案 1 :(得分:0)

我可能会这样做:

from __future__ import print_function


def process(infile, keep):
    for line in infile:
        fields = line.split()
        yield ' '.join([_ for i, _ in enumerate(fields) if i in keep])


def main(infile, outfile):
    # The following line (taken from your example) will not work in Python 3 as
    # you cannot "add" ranges to lists. In Python 3 you would need to write:
    # >>> [14] + list(range(20, 27)
    keep = range(1, 3) + [14] + range(20, 27) + range(33, 38) + [43] + [45]
    for newline in process(infile, keep):
        print(newline, file=outfile)


if __name__ == '__main__':
    with open('so.txt') as infile, open('output.txt', 'w') as outfile:
        main(infile, outfile)