0

I am trying to read a file into an array, my current implementation is only returning the first line of the .txt file

import re def GetText(filename): print('Opening file...') text_file= open(filename,'r') lines = text_file.readlines() #each line is appended to a list with text_file: one_string= text_file.read().replace('\n', '') print(one_string) 

My question is: How do I read a text file to an array?

5
  • 3
    So what's your problem? Commented Jun 29, 2015 at 14:59
  • What makes you think after using readlines() and reaching the end of file , you would get anything other than empty string from text_file.read() ? Commented Jun 29, 2015 at 14:59
  • IanAuld: He is trying to read sentences rather than just the lines of the file... Commented Jun 29, 2015 at 15:26
  • Its not appending to a new list separated by each sentence Commented Jun 29, 2015 at 16:38
  • Use a context manager to handle the file! Also, variable and function names should generally follow the lower_case_with_underscores style. Commented Nov 28, 2019 at 1:08

1 Answer 1

1

Instead of reading the whole file a line at atime why not read it all in one go and then split based on full stops (periods) in order to get sentences... ie:

text_file= open(filename,'r') data=text_file.read() listOfSentences = data.split(".") 
Sign up to request clarification or add additional context in comments.

1 Comment

He sighed, "Sure. Fine. Whatever." would not split evenly along the . character.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.