Python copy file but keep original
This question already has an answer here:
这个怎么样?
$ ls
$ touch randomfile.dat
$ ls
randomfile.dat
$ python
[...]
>>> import time
>>> src_filename = 'randomfile.dat'
>>> dst_filename = src_filename + time.strftime('.%Y%m%d%H%M')
>>> import shutil
>>> shutil.copy(src_filename, dst_filename)
'randomfile.dat.201711241929'
>>> [Ctrl+D]
$ ls
randomfile.dat
randomfile.dat.201711241929
from shutil import copy
from time import time
fn = 'random.dat'
copy(fn, fn+'.'+str(time()))
When you open the file, you can specify how you want to open it with "r"
, "w"
, or "a"
. "a"
will append to the file (r - read, w - write).
So:
with open("randomfile.dat", "a") as file:
file.write("some timestamp")
Or, if you'd like to preserve this original and make a copy, then you need to open this file, copy it, and then open a new file and write to a new file
# empty list to store contents from reading file
file_contents = []
# open file you wish to read
with open('randomfile.dat', 'r') as file:
for line in file:
file_contents.append(line)
# open new file to be written to
with open('newfile.txt', 'w') as newfile:
for element in file_contents:
newfile.write(element)
newfile.write("some timestamp")
Any line feeds (n) will be preserved by the reader and it essentially reads the file line by line. Then you write, line by line, to a new file. After the loop ends, add the timestamp so it writes to the very bottom of the file.
Edit: Just realized OP wanted to do something slightly different. This would still work but you'd need to open the new file with the timestamp appended:
import datetime
datestring = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
with open('newfile' + datestring + '.txt', 'w') as newfile:
for element in file_contents:
newfile.write(element)
But as others mention, you might be better off with a module for this.
链接地址: http://www.djcxy.com/p/42334.html下一篇: Python复制文件,但保持原来的