0

I'm new to python, I'm trying to create a list of lists from a text file. The task seems easy to do but I don't know why it's not working with my code.

I have the following lines in my text file:

word1,word2,word3,word4
word2,word3,word1
word4,word5,word6

I want to get the following output:

[['word1','word2','word3','word4'],['word2','word3','word1'],['word4','word5','word6']]

The following is the code I tried:

mylist =[]
list =[]
with open("file.txt") as f:
    for line in f:
        mylist = line.strip().split(',')
        list.append(mylist)
2
  • Your code works fine for me (although mylist =[] is useless, and you really shouldn't use list as a variable name). Don't you get the desired output when you print list? Commented Sep 29, 2017 at 15:58
  • @MedAli It's certainly good advice to not use list as a variable name, but it's not a reserved word, otherwise it would be a syntax error to use it as a variable name (try using for, while, or from as variable names). list is the name of a built-in class, and you are free to redefine it if you really want to, but generally that's not a good idea. Commented Sep 29, 2017 at 16:01

2 Answers 2

2

You can iterate like this:

f = [i.strip('\n').split(',') for i in open('file.txt')]
Sign up to request clarification or add additional context in comments.

3 Comments

You should consider extending your answer to add a with open('file.txt') as f... it's good practice :-)
This still doesn't give me the output I'm looking for :(
@Mow1993 please post the output you are receiving currently.
0

Your code works fine, if your code creating issues in your system then if you want you can do this in one line with this :

with open("file.txt") as f:
    print([i.strip().split(',') for i in f])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.