Search code examples
python-3.xtimestamppycharm

Adding timestamp to a file in PYTHON


I can able to rename a file without any problem/error using os.rename().

But the moment I tried to rename a file with timestamp adding to it, it throws win3 error or win123 error, tried all combinations but no luck, Could anyone help.

Successfully Ran Code :

#!/usr/bin/python
import datetime
import os
import shutil
import json
import re


maindir = "F:/Protocols/"
os.chdir(maindir)
maindir = os.getcwd()
print("Working Directory : "+maindir)
path_4_all_iter = os.path.abspath("all_iteration.txt")
now = datetime.datetime.now()
timestamp = str(now.strftime("%Y%m%d_%H:%M:%S"))
print(type(timestamp))
archive_name = "all_iteration_"+timestamp+".txt"
print(archive_name)
print(os.getcwd())
if os.path.exists("all_iteration.txt"):
    print("File Exists")
    os.rename(path_4_all_iter, "F:/Protocols/archive/archive.txt")
    print(os.listdir("F:/Protocols/archive/"))

print(os.path.abspath("all_iteration.txt"))

Log :

E:\python.exe C:/Users/SPAR/PycharmProjects/Sample/debug.py
Working Directory : F:\Protocols
<class 'str'>
all_iteration_20180409_20:25:51.txt
F:\Protocols
File Exists
['archive.txt']
F:\Protocols\all_iteration.txt

Process finished with exit code 0

Error Code :

    print(os.getcwd())
if os.path.exists("all_iteration.txt"):
    print("File Exists")
    os.rename(path_4_all_iter, "F:/Protocols/archive/"+archive_name)
    print(os.listdir("F:/Protocols/archive/"))

print(os.path.abspath("all_iteration.txt"))

Error LOG:

E:\python.exe C:/Users/SPAR/PycharmProjects/Sample/debug.py
Traceback (most recent call last):
Working Directory : F:\Protocols
<class 'str'>
  File "C:/Users/SPAR/PycharmProjects/Sample/debug.py", line 22, in <module>
all_iteration_20180409_20:31:16.txt
F:\Protocols
    os.rename(path_4_all_iter, "F:/Protocols/archive/"+archive_name)
File Exists
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'F:\\Protocols\\all_iteration.txt' -> 'F:/Protocols/archive/all_iteration_20180409_20:31:16.txt'

Process finished with exit code 1

Solution

  • Your timestamp format has colons in it, which are not allowed in Windows filenames. See this answer on that subject:

    How to get a file in Windows with a colon in the filename?

    If you change your timestamp format to something like:

    timestamp = str(now.strftime("%Y%m%d_%H-%M-%S"))
    

    it should work.