Python:我如何为每个读取的文件获得一个新的列? [英] Python : How do i get a new column for every file I read?

查看:488
本文介绍了Python:我如何为每个读取的文件获得一个新的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取3个文本文件,并将它们合并成一个输出文件。到目前为止这么好,唯一的问题是,我需要为我读的每个文件创建列。现在我已经从单个列中的文件中提取了所有的数据。

$ p $ #!/ usr / bin / env python

导入sys
usage ='用法:%s infile'%sys.argv [0]

i = 3#开始位置
outfile = open( 'outfil.txt','w')

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

outfile.write(infilename +'\\\
')
用于ifile行:
outfile.write(line)
打印行
除外:
打印用法; sys.exit [i]

i + = 1;

现在我的输出文件如下所示:

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


解决方案

打开输入文件一个接一个,收集数据到列表中。然后, zip()数据和作者通过 csv 作家以空格作为分隔符:


$ b $

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

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

data = []
for 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)



  • 1。

      1 
    2
    3
    4
    5


  • 2.txt 与以下内容:

      6 
    7
    8
    9
    10




您将代码保存到 test.py ,并将其作为运行python test.py 1.txt 2.txt ,在 outfil.txt 您将得到:

  1 6 
2 7
3 8
4 9
5 10


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

解决方案

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

这篇关于Python:我如何为每个读取的文件获得一个新的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆