1

I've a text.txt looking like that :

login1 fname1 lname1 mail1\n 
login2 fname2 lname2 mail2\n 
login3 fname3 lname3 mail3\n 
login4 fname4 lname4 mail4\n 
...

My goal is to create a list of each line to a list of all line, like that :

lst = [[login1, fname1, lname1, mail1],[login2, fname2, lname2, mail2],...]

I've make a script who make a list of each line, but I can't make a list inside the line... (I hope you understand...)

I've seen this link building-a-list-from-a-text-file-in-python but it's for number and I've fail to reproduc for string.

Here is my beginnig script :

file = "export_user.txt"
if os.path.exists(file):
    file = open("export_user.txt", "r") #.readlines()
    list_name = []
    i = 0
    for line in file:
        list_name.append(line)
        list_name[i] = list_name[i].strip()
        i += 1
        print(list_name)

    # with open(file) as f:
        # lst = [map(str(), str()) for line in f]
        # print (lst[0])
5
  • why are you adding 1 to i? Commented Mar 13, 2015 at 14:53
  • When you do list_name.append(line), you probably want to first split line up into it's components (e.g. with line_parts = line.split()), and then append line_parts to list_name. Commented Mar 13, 2015 at 14:53
  • @AvinashRaj I increment i to remove for each list the \n Commented Mar 13, 2015 at 14:57
  • is login1, fname1, lname1, mail1 a whole string or list elements? Commented Mar 13, 2015 at 14:59
  • @AvinashRaj a whole strin, wich I want to transform on a list elements for each lines Commented Mar 13, 2015 at 15:00

2 Answers 2

2

You could try the below.

with open("file", "r") as f:
    m = f.readlines()
    print [i.strip().split() for i in m]

Output:

[['login1', 'fname1', 'lname1', 'mail1'], ['login2', 'fname2', 'lname2', 'mail2'], ['login3', 'fname3', 'lname3', 'mail3'], ['login4', 'fname4', 'lname4', 'mail4']]
Sign up to request clarification or add additional context in comments.

3 Comments

@AvinashRaj That's not so far, but instead of separate each element by , I want a list
just an intermediate variable to hold the list element for each iteration.
Ok that's work with l = [i.strip().split() for i in m] print(l)
0
a="""login1 fname1 lname1 mail1 
login2 fname2 lname2 mail2 
login3 fname3 lname3 mail3 
login4 fname4 lname4 mail4"""

l = [x.strip().split(" ") for x in a.strip().split("\n")]

[['login1', 'fname1', 'lname1', 'mail1'],
 ['login2', 'fname2', 'lname2', 'mail2'],
 ['login3', 'fname3', 'lname3', 'mail3'],
 ['login4', 'fname4', 'lname4', 'mail4']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.