How to use the list() function on a text file, to make turn the text file into a list of characters?

How would i do that?

#The code
f = open('/storage/emulated/0/files/text.txt', 'r')
text =
char = list(text)

Heres the text file

I want the result to be:

[‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]

But instead I get just empty square brackets.

Strange, the code you provide should already work. Do you have a larger example that may show what’s going on?

By the way, don’t open and read files like that. You should do

with open(file_name, "r") as f:
    text =

or using the pathlib module

from pathlib import Path

text = Path(file_name).read_text()

(edited: spelling)

This ensures the file is closed properly.

that is actually all my code, I was trying something out, thanks for the advice tho!

turns out I wrote the wrong address for the file. Just took ur advice and fixed it and now it works Thanks!

We constantly urge people to reduce code to the minimum needed to expose the problem, and to put minimal example data sources in the code example rather than leaving them in external data sources. If you had tried to do so, you would have discovered that the only way for list(somestring) to be [] is when somestring == ''.

1 Like