作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试读取 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/
我是一名优秀的程序员,十分优秀!