2

I have 10 txt files. Each of them with strings.

A.txt: "This is a cat"
B.txt: "This is a dog"
.
.
J.txt: "This is an ant"

I want to read these multiple files and put it in 2D array.

[['This', 'is', 'a', 'cat'],['This', 'is', 'a', 'dog']....['This', 'is', 'an', 'ant']]

from glob import glob
import numpy as np
for filename in glob('*.txt'):
    with open(filename) as f:
        data = np.genfromtxt(filename, dtype=str)

It's not working the way I want. Any help will be greatly appreciated.

1 Answer 1

2

You are just generating different numpy arrays for each text file and not saving any of them. How about add each file to a list like so and convert to numpy later?

data = []

for filename in glob('*.txt'):
    with open(filename) as f:
        data.append(f.read().split())

data = np.array(data)
Sign up to request clarification or add additional context in comments.

2 Comments

Can you just explain how does it line help? - data.append(f.read().split())
it is because we are keeping a list of all of the text in the files. f.read().split() would produce ['This', 'is', 'a', 'cat'] for a file containing 'This is a cat' and so appending that to data gives the desired 2d array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.