我有 10 个 txt 文件。每个都带有字符串。
A.txt: "This is a cat"
B.txt: "This is a dog"
.
.
J.txt: "This is an ant"
我想读取这些多个文件并将其放入二维数组中。
[['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)
它没有按照我想要的方式工作。任何帮助将不胜感激。
最佳答案
您只是为每个文本文件生成不同的 numpy 数组,而不保存任何它们。像这样将每个文件添加到列表中并稍后转换为 numpy 怎么样?
data = []
for filename in glob('*.txt'):
with open(filename) as f:
data.append(f.read().split())
data = np.array(data)
关于python-3.x - 在Python中将多个文本文件读取到二维numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55794954/