Triath
Triath

Reputation: 31

How to split a list using python 3?

I'm trying to combine multiple lines and split them by tabs :

with open('combined.txt', "r") as f:
    print(' '.join(line.strip("\n").split("\t") for line in f))

but I am getting this error:

TypeError: sequence item 0: expected str instance, list found.

input:

azubi
arch=pc
mhz#2666
os=linux
ipv6net=auto

adrian
arch=pc
memory#4096
os=solaris11
osdist=opensolaris

desired output:

azubi arch=pc mhz#2666 os=linux ipv6net=auto <
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

Upvotes: 0

Views: 112

Answers (2)

PyPingu
PyPingu

Reputation: 1747

So whilst I think the other answers have solved the error, they aren't giving you the intended output.

I am making the assumption that the text that forms 1 line in the output is always separated by a single blank line, as in your sample input.

I have two possible solutions:

Method 1:

with open('test.txt', 'r') as in_f:
    content=in_f.read()


content2 = content.splitlines()
new_lines = []
while content2:
    try:
        split_idx = content2.index('')
        new_lines.append(content2[0:split_idx])
        content2 = content2[split_idx+1:]
    except ValueError as e:
        new_lines.append(content2)
        content2 = False

for line in new_lines:
    print(' '.join(line))

azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

Method 2:

with open('test.txt', 'r') as in_f:
    content=in_f.read()

content2 = content.splitlines()

size = len(content2) 
idx_list = [idx + 1 for idx, val in enumerate(content2) if val == '']

res = [content2[i: j] for i, j 
    in zip([0] + idx_list, idx_list + 
    ([size] if idx_list[-1] != size else []))] 

for line in res:
    print(' '.join(line).strip())

azubi arch=pc mhz#2666 os=linux ipv6net=auto
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris

Upvotes: 0

Kampi
Kampi

Reputation: 1891

You can use this snippet to read and format your data, assuming that your data are seperated by a newline.

Outputs = list()
Output = str()
with open('Test.txt', "r") as f:
    for line in f:
        line = line.strip()
        if(len(line)):
            Output += "{} ".format(line)
        else:
            Outputs.append(Output)
            Output = str()

for Output in Outputs:
    print("".join(Output))

This gives the output:

azubi arch=pc mhz#2666 os=linux ipv6net=auto 
adrian arch=pc memory#4096 os=solaris11 osdist=opensolaris 

Upvotes: 1

Related Questions