简体   繁体   中英

How to concatenate a file in Python

I am a newbie to Python and trying to concatenate three file side by side (much explanation in the example)

file1

localhost
localhost1

file2

127.0.0.1
127.0.0.2

file3

localhost.example.com
localhost.example.com

code

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) 

But this is producing output as

localhost
localhost1
127.0.0.1
127.0.0.2
localhost.example.com
localhost1.example.com

But I need output as:

localhost 127.0.0.1 localhost.example.com
localhost1 127.0.0.2 localhost1.example.com

OR BETTER AS LIST

[[localhost,127.0.0.1,localhost.example.com],[localhost1 127.0.0.2 localhost1.example.com]]

OR FINAL BEST OPTION

{"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"]]

For your third option (assuming you want it in JSON format):

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)

You can read multiple file at once using izip_longest :

Code:

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()

Results:

localhost   127.0.0.1   localhost.example.com
localhost1  127.0.0.2   localhost.example.com

As a List:

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)

Results:

['localhost', '127.0.0.1', 'localhost.example.com']
['localhost1', '127.0.0.2', 'localhost.example.com']

Here's a modified script of yours:

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 became:

[{'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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM