I have a text file that consists of some text.
I want to import this into an array consisting of characters, Ex: a file containing "Hello" would become
['h', 'e', 'l', 'l', 'o']
.
I tried using loadtxt (which I usually use for reading data from files) but I think it can only handle actual data (with numbers and stuff). How do I do it?
This is the usual way to read an entire file:
with open("file") as f:
content = f.read()
You can then call list(content)
to get a list from the string.
If you want to load strings using loadtxt
:
import numpy as np
text = np.loadtxt(filepath, dtype = np.str)
As others are mentioning, there are other ways of doing this. Furthermore, you can access the individual characters of a string in much the same way as a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With