python怎么隔一个读取一个_Python:我如何为每个读取的文件获得一个新的列?

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

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值