我是python的新手。我为机器学习项目编写了以下代码。代码应该遍历文件夹中的文本文件,然后从中读取所有行。
import glob
files = glob.glob("corpus/*.txt")
for fle in files:
with open(fle) as f:
text = f.readlines()
print text
输出:
['enim, et rutrum lorem placerat in']
['lorem in magna volutpat sodale']
['Fusce nec felis suscipit']
['Vivamus ultrices neque eget leo']
如何更改代码以获得如下输出:
['enim, et rutrum lorem placerat in','lorem in magna volutpat sodale','Fusce nec felis suscipit','Vivamus ultrices neque eget leo']
答案 0 :(得分:3)
只需在您正在阅读文件时连接您的列表,例如:
import glob
lines = [] # store for your lines
files = glob.glob("corpus/*.txt")
for fle in files:
with open(fle) as f:
lines += f.readlines()
print(lines)