gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:36:37 27 4
gpt4 key购买 nike

我正在尝试读取 3 个文本文件并将它们组合成一个输出文件。到目前为止一切顺利,唯一的问题是我需要为我读取的每个文件创建列。现在,我将从文件中提取的所有数据都放在一列中。

  #!/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;

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

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

最佳答案

依次打开输入文件,将数据收集到列表列表中。然后,zip()通过csv writer将数据和writer以空格作为分隔符:

#!/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)

假设你有:

  • 1.txt 包含以下内容:

    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

关于 python : How do i get a new column for every file I read?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18834876/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com