Mow1993
Mow1993

Reputation: 89

Create list of lists from file python

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)

Upvotes: 0

Views: 4023

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12669

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])

Upvotes: 0

Ajax1234
Ajax1234

Reputation: 71451

You can iterate like this:

f = [i.strip('\n').split(',') for i in open('file.txt')]

Upvotes: 2

Related Questions