我试图读取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
答案 0 :(得分:1)
一个接一个地打开输入文件,将数据收集到列表列表中。然后,zip()
数据和作者通过csv
编写者以空格作为分隔符:
#!/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
答案 1 :(得分:1)
$ 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
>>>