Python : How do i get a new column for every file I read?

蓝咒 提交于 2019-12-11 09:07:42

问题


Im trying to read 3 text files and combine them into a single output file. so far so good, the only problem is that I need to create columns for every file i read. right now I have all the extracted data from the files in a single column.

  #!/usr/bin/env python

    import sys
    usage = 'Usage: %s infile' % sys.argv[0]

    i=3 #start position
    outfile = open('outfil.txt','w')

    while i<len(sys.argv):
        try:
            infilename = sys.argv[i]
        ifile = open(infilename, 'r')

        outfile.write(infilename+'\n')
        for line in ifile:
            outfile.write(line) 
            print line 
        except:
            print usage; sys.exit[i]

        i+=1; 

right now my output file looks like this:

test1.txt
a
b
c
d
test2.txt
e
f 
g
h
test3.txt
i
j
k
l

回答1:


Open input files one after another, collect data into the list of lists. Then, zip() the data and writer via csv writer with space as a delimiter:

#!/usr/bin/env python
import csv
import sys

usage = 'Usage: %s infile' % sys.argv[0]

data = []
for filename in sys.argv[1:]:
    with open(filename) as f:
        data.append([line.strip() for line in f])

data = zip(*data)
with open('outfil.txt', 'w') as f:
    writer = csv.writer(f, delimiter=" ")
    writer.writerows(data)

Assuming you have:

  • 1.txt with the following contents:

    1
    2
    3
    4
    5
    
  • 2.txt with the following contents:

    6
    7
    8
    9
    10
    

Then, if you save the code to test.py and run it as python test.py 1.txt 2.txt, in outfil.txt you will get:

1 6
2 7
3 8
4 9
5 10



回答2:


$ cat a
1
2
3
4
5
6
7
8
9
10

$ cat b
51
52
53
54
55
56
57
58
59
60


>>> import itertools
>>> for (i,j) in itertools.izip(open('a'), open('b')):
...     print i.strip(), '---', j.strip()
...
1 --- 51
2 --- 52
3 --- 53
4 --- 54
5 --- 55
6 --- 56
7 --- 57
8 --- 58
9 --- 59
10 --- 60


>>>


来源:https://stackoverflow.com/questions/18834876/python-how-do-i-get-a-new-column-for-every-file-i-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!