David R
David R

Reputation: 23

Storing contents of each individual text file to a list

I'm trying to store the entire contents of each text file to an element in a list.

I've tried doing this using nltk but it puts every letter of the text as an element in the list which is not what I want.

Is there any way of doing this using nltk or normal python as the only examples I have seen online put each line as an element whereas I want the entire document.

My code:

textfile_list = [file1.txt, file2.txt, file3.txt ........ file76.txt]

for f in textfile_list:
    
    file_text=nltk.data.load('/user/documents'+f)
    text+= file_text


print(text)

Upvotes: 1

Views: 561

Answers (1)

AziMez
AziMez

Reputation: 2082

Try this one, it should store each text file to an element in the list.

textfile_list = ['file1.txt', 'file2.txt', 'file3.txt']
list=[]
for f in textfile_list: 
    file_text=open(f,'r').read()
    list.append(file_text) 


print(list[0])
print(list[1])
print(list[2])

Upvotes: 2

Related Questions