[英]How to concatenate a file in Python
我是Python的新手,尝试并排连接三个文件(示例中的很多解释)
localhost
localhost1
127.0.0.1
127.0.0.2
localhost.example.com
localhost.example.com
filenames = ['file1', 'file2', 'file3']
with open('final_outoput.txt', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
但这会产生输出
localhost
localhost1
127.0.0.1
127.0.0.2
localhost.example.com
localhost1.example.com
但我需要输出为:
localhost 127.0.0.1 localhost.example.com
localhost1 127.0.0.2 localhost1.example.com
或更好的列表
[[localhost,127.0.0.1,localhost.example.com],[localhost1 127.0.0.2 localhost1.example.com]]
或最后的最佳选择
{"hostname":"localhost","ip_address":127.0.0.1,"lb_name":"localhost.example.com"],["hostname":"localhost1","ip_address":127.0.0.2,"lb_name":"localhost1.example.com"]]
对于第三个选项(假设您希望使用JSON格式):
import json
with open('file1') as f1, open('file2') as f2, open('file3') as f3, open('final_outoput.txt', 'w') as outfile:
json.dump([
{'hostname': h, 'ip_address': i, 'lb_name': l}
for h, i, l in zip(*(f.read().splitlines() for f in (f1, f2, f3)))
], outfile)
您可以使用izip_longest
一次读取多个文件:
filenames = 'file1 file2 file3'.split()
import itertools as it
with open('final_output.txt', 'w') as outfile:
files = [open(fname, 'rU') for fname in filenames]
for text in it.zip_longest(*files):
outfile.write(
'\t'.join(t.strip() if t else '' for t in text) + '\n')
for f in files:
f.close()
localhost 127.0.0.1 localhost.example.com
localhost1 127.0.0.2 localhost.example.com
import itertools as it
output = []
with open('final_output.txt', 'w') as outfile:
files = [open(fname, 'rU') for fname in filenames]
for text in it.zip_longest(*files):
output.append(list(t.strip() if t else '' for t in text))
for f in files:
f.close()
for data in output:
print(data)
['localhost', '127.0.0.1', 'localhost.example.com']
['localhost1', '127.0.0.2', 'localhost.example.com']
这是您的修改后的脚本:
filenames = ['file1', 'file2', 'file3']
d=[]
for fname in filenames:
d.append([])
with open(fname+'.txt') as infile:
for line in infile:
d[-1]+=[line.strip()]
d=zip(*d)
with open('final_outoput.txt', 'w')as outfile:
outfile.write(str(list(map(lambda x:dict(hostname=x[0],id_address=x[1],lb_name=x[2]),d))))
outoput.txt
变成:
[{'id_address': '127.0.0.1', 'lb_name': 'localhost.example.com', 'hostname': 'localhost'}, {'id_address': '127.0.0.2', 'lb_name': 'localhost.example.com', 'hostname': 'localhost1'}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.