user2330621
user2330621

Reputation: 101

Splitting characters from a text file in Python

So I am importing a txt with say

abc
dfg
fgh

contained in the txt file. Though currently I am getting it in the form of

[[abc],[dgf],[fgh],]

When im trying to get

[['a','b','c'],['d','g','f'],['f','g','h']]

My currently code is

f = open(filename, 'rU')
result = [line.list(',') for line in f.readlines()]

How can I change this to get it to seperate each character in the lists?

Upvotes: 2

Views: 7172

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250981

Use just list(line.rstrip()), list() can convert a string to list of single characters:

with open('filname') as f:
    result = [list(line.rstrip()) for line in f]

And don't use file.readlines, you can iterate over the file object itself.

Demo:

>>> list("foobar")
['f', 'o', 'o', 'b', 'a', 'r']

Upvotes: 1

Related Questions