Reputation: 113
I have been trying to read a text documents easily using the code below, however I don't want to read the entire text documents, let's say the total length of the words in the text documents is 2,845.
for line in open('foo.txt', "r"):
print(line)
i want to read the first 1,674 words from the documents
Thanks in advance
Upvotes: 1
Views: 193
Reputation: 2518
First of all, you should always use with open()
to open and read a file, as the file gets closed automatically. In total it's less error prone and more readable.
Concerning your problem, here is a short snippet which should push you forward:
with open('foo.txt', 'r') as file:
text = file.read().replace('\n', ' ')
words = text.split(' ')
char_limited_text = ' '.join(words[:1674]
The above code works in three steps:
text
If performance counts, there might be a better solution reading the file line by line and to keep track of how much words are read in already.
Upvotes: 2