Niati Arora
Niati Arora

Reputation: 129

generating list by reading from file

i want to generate a list of server addresses and credentials reading from a file, as a single list splitting from newline in file.

file is in this format

login:username
pass:password
destPath:/directory/subdir/
ip:10.95.64.211
ip:10.95.64.215
ip:10.95.64.212
ip:10.95.64.219
ip:10.95.64.213

output i want is in this manner

[['login:username', 'pass:password', 'destPath:/directory/subdirectory', 'ip:10.95.64.211;ip:10.95.64.215;ip:10.95.64.212;ip:10.95.64.219;ip:10.95.64.213']]

i tried this

with open('file') as f:
credentials = [x.strip().split('\n') for x in f.readlines()]

and this returns lists within list

[['login:username'], ['pass:password'], ['destPath:/directory/subdir/'], ['ip:10.95.64.211'], ['ip:10.95.64.215'], ['ip:10.95.64.212'], ['ip:10.95.64.219'], ['ip:10.95.64.213']]

am new to python, how can i split by newline character and create single list. thank you in advance

Upvotes: 0

Views: 61

Answers (3)

Paul Rooney
Paul Rooney

Reputation: 21619

You could do it like this

with open('servers.dat') as f:
    L = [[line.strip() for line in f]]
print(L)

Output

[['login:username', 'pass:password', 'destPath:/directory/subdir/', 'ip:10.95.64.211', 'ip:10.95.64.215', 'ip:10.95.64.212', 'ip:10.95.64.219', 'ip:10.95.64.213']]

Just use a list comprehension to read the lines. You don't need to split on \n as the regular file iterator reads line by line. The double list is a bit unconventional, just remove the outer [] if you decide you don't want it.

I just noticed you wanted the list of ip addresses joined in one string. It's not clear as its off the screen in the question and you make no attempt to do it in your own code.

To do that read the first three lines individually using next then just join up the remaining lines using ; as your delimiter.

def reader(f):
    yield next(f)
    yield next(f)
    yield next(f)
    yield ';'.join(ip.strip() for ip in f)

with open('servers.dat') as f:
    L2 = [[line.strip() for line in reader(f)]]

For which the output is

[['login:username', 'pass:password', 'destPath:/directory/subdir/', 'ip:10.95.64.211;ip:10.95.64.215;ip:10.95.64.212;ip:10.95.64.219;ip:10.95.64.213']]

It does not match your expected output exactly as there is a typo 'destPath:/directory/subdirectory' instead of 'destPath:/directory/subdir' from the data.

Upvotes: 2

Zach Ward
Zach Ward

Reputation: 127

You could just treat the file as a list and iterate through it with a for loop:

arr = []
with open('file', 'r') as f:
    for line in f:
        arr.append(line.strip('\n'))

Upvotes: 0

Bishal
Bishal

Reputation: 837

This should work

arr = []
with open('file') as f:
    for line in f:
        arr.append(line)
return [arr]

Upvotes: 0

Related Questions