How to Read a Text File into a List or an Array with Python

Python read text file into an array of words

You have to call split() on each separate line.

words = []
lines = fileObj.read().splitlines()
for line in lines:
words.extend(line.split())

How to Import and extract elements from a list of arrays saved as a text file in python

If the file content is, for example:

array([1,2,3])

...then...

from numpy import array
with open('filename.txt') as f:
a = eval(f.read())
print(a)
print(type(a))

...will produce...

[1 2 3]
<class 'numpy.ndarray'>

Importing array list in text file into Python

To read the data from your txt file and store it as a list in Python, you can use the following code:

with open('path/to/your/file.txt', 'r') as file: data = file.read()
myList = data.split()


Related Topics



Leave a reply



Submit