Cedric Huang
Cedric Huang

Reputation: 1

converting the lines of the file into a tuple of list in python 3

In my python file:

And I would like to convert it into this in python 3:

([10], ['a7','j7','d10','g10'], ['d1','g1','a4','j4'], ['a3','b3','c3','d3','e3'])

But the last line ['a3','b3','c3','d3','e3'] can return an empty list if there isn't a fourth line.

I have opened the file but can't convert it into a tuple of lists.

1

Upvotes: 0

Views: 570

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

$ echo "10
a7,j7,d10,g10
d1,g1,a4,j4
a3,b3,c3,d3,e3" > my_file.txt

$ echo "10
a7,j7,d10,g10
d1,g1,a4,j4
" > my_file2.txt

You can use a comprehension to process each line of the file, and feed that to tuple(). In this case, it looks like what you want to do is split each line on the comma (turning the one comma-separated string that is each line, into a list of strings without commas), but if the line is empty or contains only whitespace, add an empty list instead.

def process_file(filename):
    with open(filename) as infile:
        return tuple(
            line.strip().split(',') if line.strip() else [] 
            for line in infile
        )

process_file('my_file.txt')
# (['10'], ['a7', 'j7', 'd10', 'g10'], ['d1', 'g1', 'a4', 'j4'], ['a3', 'b3', 'c3', 'd3', 'e3'])

process_file('my_file2.txt')
# (['10'], ['a7', 'j7', 'd10', 'g10'], ['d1', 'g1', 'a4', 'j4'], [])

If you wanted to omit the empty list entirely if the line is blank, then you can move the condition if line.strip() to after for line in infile, and remove the else clause. This will cause the comprehension to just ignore empty lines, not adding anything to the tuple for them.

Upvotes: 2

Related Questions