combining one-column text files into one multi-column file, separated by tabs

后端 未结 2 1010
别跟我提以往
别跟我提以往 2021-01-26 04:39

I have several one-column text files that I want to put next to each other (e.g. each file is one column). The only documentation I could find was on appending files to the bott

2条回答
  •  猫巷女王i
    2021-01-26 05:32

    I would rewrite your code as follows:

    import glob
    from itertools import izip
    
    def extract_meaningful_info(line):
        return line.rstrip('\n').split('[')[0]
    
    MA_files = glob.glob("MA*continuous*2")
    
    with open("MA_continuous_results.csv", "wb") as outfile:
        outfile.write("\t".join(MA_files) + '\n')
        for fields in izip(*(open(f) for f in MA_files)):
            fields = [extract_meaningful_info(f) for f in fields]
            outfile.write('\t'.join(fields) + '\n')
    

    (code is for python2)

    You might want to read about:

    • itertools.izip

    • * in the arguments of function

提交回复
热议问题