Tuesday 30 August 2016

timestamp - Python copy file but keep original




Python query.



I want to take a copy of a file, called randomfile.dat, and add a timestamp to the end of the copied file.



However, I want to keep the original file too. So in my current directory (no moving files) I would end up with:
randomfile.dat
randomfile.dat.201711241923 (or whatever the timestamp format is..)



Can someone advise? Anything I have tried causes me to lose the original file.



Answer



How about this?



$ 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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...