Chinmay Nayak
Chinmay Nayak

Reputation: 273

Python: unable to produce the output in list format

I want to produce the output in a list format but I am failing.

It's taking some login details from a text file:

Ip1,username1,pwd1

Ip2,username2,pwd2

Ip3,username3,pwd3

Ip4,username4,pwd4

My Python script:

import os.path

save_path = "C:\Users\Public\Pythonlearn"

input_pwd_file= os.path.join(save_path,'loginfile'+'.txt')

with open(input_pwd_file) as f:

    list = []

    for line in f:

        list.append(line)


    a=list[3] 

print "login details: ",a

I am getting below output:

login details: Ip4,username4,pwd4

But I want it to be like:

login details: ['Ip4','username4','pwd4']

Upvotes: 0

Views: 35

Answers (2)

alex
alex

Reputation: 2541

Change a=list[3] to a=list[3].split(',') and as beruic said, don't name your list 'list'

Upvotes: 0

beruic
beruic

Reputation: 5876

Well, you are just appending the raw line to the list, instead of parsing it. So, it is expected that the lines in the list is exactly the same as the lines in the file. A simple way to parse the line is by using str.split() and do line_as_list = line.split(','). From there it's just a matter of using the list to make a string from.

Final note: Don't call your list variable list. That shadows the built-in constructor to build a list with.

Upvotes: 1

Related Questions