Jami
Jami

Reputation: 23

iterate through directory of txt files and print the output as a single list

I am very new to python. I have written the following code for a machine learning project. The code is supposed to iterate through text files in a folder and then read all the lines from it.

import glob

files = glob.glob("corpus/*.txt")
for fle in files:
   with open(fle) as f:
      text = f.readlines()
      print text

It outputs this:

['enim, et rutrum lorem placerat in']
['lorem in magna volutpat sodale']
['Fusce nec felis suscipit']
['Vivamus ultrices neque eget leo']

How can I change my code to get an output like this:

['enim, et rutrum lorem placerat in','lorem in magna volutpat sodale','Fusce nec felis suscipit','Vivamus ultrices neque eget leo']

Upvotes: 2

Views: 1422

Answers (1)

zwer
zwer

Reputation: 25789

Just concatenate your list as you're reading the files in, something like:

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)

Upvotes: 4

Related Questions