-1

I'm using Python 3.65 on Windows 7.

In my little clipboard saver program, I save the current clipboard text to a text file with time and date, and each time the user wants to save again another paste is added to the file. (see function below)

My question is, is there a way to append the next text to the top of the text file so the most recent save is first in the file?

ct=time.asctime()          #get system time and date in ct
cb_txt = pyperclip.paste() #store clipboard in cb_txt

f = open("c:\\cb-pastes\\saved.txt","a") # open the file:
f.write ("\n")                           #newline
f.write (ct)                             #save date and time with the text
f.write ("\n")
f.write (cb_txt)                         #append to text file      
f.write ("\n")
f.write ("-----------------------------")  
f.close()                               #Close the file

Example of the output:(I want the latest at the beginning of the file)

Thu Jun 21 11:14:15 2018
button1
-----------------------------
Thu Jun 21 11:28:05 2018
Example of the output:
-----------------------------
Thu Jun 21 11:28:25 2018
https://stackoverflow.com/questions/ask
-----------------------------

For a screenshot of this:

screenshot

Regards, Steve.

aduguid
  • 3,099
  • 6
  • 18
  • 37
Steve S
  • 84
  • 1
  • 9

1 Answers1

3

Here's a simple solution: Create a temporary file and add the header date in it and then append the original data. Finally just rename it to the same file name

import os
def insert(oldfile,string):
  with open(oldfile,'r') as f:
    with open('newfile.txt','w') as f2: 
      f2.write(string)
      f2.write(f.read())
  os.rename('newfile.txt',oldfile)

Ref: Prepend line to beginning of a file

Jongware
  • 22,200
  • 8
  • 54
  • 100
Vivek
  • 123
  • 7