-2

Update: Thanks guys for the help I finally figured it out. I don't know why i didnt use other libraries (brain fart moment) I'll link the working code below. The alternative answers work but dont keep the same lines as they were before.

The working code:

log_file = open("bigfile.txt", "rt")
contents = log_file.read()
words = contents.split(' ') #added space here
log_file.close() 

write_file = open("info.txt",'w') # we wipe everything in the file

# slice the file's content
words_to_add = words[-1000:] #like @jpa suggested 

for w in words_to_add: # Add the first words
    write_file.write(w + " ")


write_file.close()

  • Check the `tail` [recipe](https://docs.python.org/3/library/collections.html#deque-recipes) in the collections module. – dawg Sep 10 '22 at 16:52

2 Answers2

1

I think the following could do the trick:

# read the file's contents
log_file = open("./static/logs/content.log", "rt")
contents = log_file.read()
words = contents.split(' ') #added space here
log_file.close() 

write_file = open("info.txt",'w') # we wipe everything in the file

# slice the file's content
words_to_add = words[-1000:] #like @jpa suggested 

for w in words_to_add: # Add the first words
    write_file.write(w)


write_file.close()

Also, suggest some to check some content on how to do this in multiple ways.

Note: this way you read all the content right away, which is usually not used in practice, but rather line by line, etc.

Warkaz
  • 845
  • 6
  • 18
0
import re
log_file = open("./static/logs/content.log", "rt")

contents = log_file.read()
words = re.findall(r'\S+|\n', contents)

new_text = ' '.join(words[-1000:])
print (new_text)

Is this what you need?