Suppose I have some text I want to split into chunks that end up in separate text files (and I want to use mozway's solution to that task found here), how do I add incremental timestamps to the text before splitting?
So, imagine the .txt file I want to updated is as follows:
name:: Joe Blogs
phone:: 123456789
email:: joeblogs@email.com
address:: 123 Main Street
note:: blah blah blah
timestamp::
name:: Josephine Blogs
phone:: 43217890
email:: josephineblogs@email.com
address:: 123 Main Street
note:: More blah blah
timestamp::
name:: John Smith
phone:: 23498689
email:: johnsmith@email.com
address:: 1 North Street
note:: Some more blah
timestamp::
...and I want to add a timestamp to each chunk, separated by 1 second. The result would look like this:
name:: Joe Blogs
phone:: 123456789
email:: joeblogs@email.com
address:: 123 Main Street
note:: blah blah blah
timestamp:: 2022-07-15 (14h 55m 23s)
name:: Josephine Blogs
phone:: 43217890
email:: josephineblogs@email.com
address:: 123 Main Street
note:: More blah blah
timestamp:: 2022-07-15 (14h 55m 24s)
name:: John Smith
phone:: 23498689
email:: johnsmith@email.com
address:: 1 North Street
note:: Some more blah
timestamp:: 2022-07-15 (14h 55m 25s)
I then want to split this text using the working solution that mozway gave here.
I tried the following code but it didn't work...
import time
with open('file.txt') as f:
for line in f:
if line.startswith('timestamp::'):
t = time.localtime()
timestamp = time.strftime('%Y-%m-%d (%Hh %Mm %Ss)', t)
line = line + timestamp
time.sleep(1)
for n, chunk in enumerate(f.read().split('\n\n'), start=1):
with open(f'chunk_{n}.txt', 'w') as f_out:
f_out.write(chunk)
Only one file was generated, 'chunk_1.txt', and it was empty; it had no content.