1

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)
David R
  • 23
  • 5
  • 1
    Does this answer your question? [How to read a text file into a string variable and strip newlines?](https://stackoverflow.com/questions/8369219/how-to-read-a-text-file-into-a-string-variable-and-strip-newlines) – hopperelec Oct 23 '21 at 18:23
  • No @hopperelec it still does it letter by letter – David R Oct 23 '21 at 18:28

1 Answers1

2

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])
AziMez
  • 2,014
  • 1
  • 6
  • 16