Tuesday, April 30, 2019

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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...