我尝试使用以下脚本组合两个不同的xml文件......
filenames = ['file1', 'file2']
with open('file3', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
print 'done'
它有效,但不是我想要的方式。而不是将不同的列放入它们自己的列中,这两个文件像这样叠加在一起
time1 time2
1 2
1 3
2 3
2 4
speed date number
4 1 1
4 1 2
8 1 3
8 1 4
......但我想要这样......
speed date number time1 time2
4 1 1 1 2 1 2
4 1 2 1 3 1 3
8 1 3 2 3 2 3
8 1 4 2 4 2 4
建议?
答案 0 :(得分:2)
你应该使用内置的csv模块
list1 = map(list,csv.reader(open("text1")))
list2 = map(list,csv.reader(open("text2")))
with open("combined.txt","wb") as f:
csv.writer(f).write_rows(zip(*(zip(*list1)+zip(*list2))))
但你可以在没有
的情况下完成list1 = map(str.split,open("text1"))
list2 = map(str.split,open("text2"))
with open("combined.txt","wb") as f:
f.write("\n".join(map(" ".join,row) for row in zip(*(zip(*list1)+zip(*list2)))))
(我认为我有足够的匹配括号)
甚至更简单
with open("file3.txt","wb") as f:
for row1,row2 in zip(open("file1"),open("file2")):
f.write("%s\t%s\n"%(row1.strip(),row2.strip()))