我可以附加到文本文件的开头吗?

时间:2018-06-21 10:36:49

标签: python-3.x

我正在Windows 7上使用Python 3.65。

在我的剪贴板保存程序小程序中,我将当前剪贴板文本保存到带有时间和日期的文本文件中,每次用户想要再次保存时,都会向该文件中添加另一个粘贴。 (请参见下面的功能)

我的问题是,有没有一种方法可以将下一个文本附加到文本文件的顶部,以便最近一次保存在文件的第一个?

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

输出示例:(我想在 文件的开头)

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
-----------------------------

有关此屏幕截图:

screenshot

关于,史蒂夫。

1 个答案:

答案 0 :(得分:2)

这是一个简单的解决方案: 创建一个临时文件,并在其中添加标题日期,然后附加原始数据。最后,只需将其重命名为相同的文件名

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)

参考:Prepend line to beginning of a file