Raj Rajeshwari Prasad
Raj Rajeshwari Prasad

Reputation: 334

Adding timestamp to File name in Python

I want to add a timestamp to my file name for the ease to recognize the latest file.

for this, I tried the following code:-

csv_file = pd.read_csv('C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/csv_files/all_web_final_ds.csv',usecols=['page_title'])
page_tile_list=list(csv_file['page_title'])

filename1 = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
timestamp_string = str(filename1)
with open('C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/text_files/all_ds_pagetitles.txt' + timestamp_string,'w',encoding='utf-8',) as f:
    for item in page_tile_list:
        f.write('%s\n'%item)

unfortunately, I am getting an error as

OSError: [Errno 22] Invalid argument: 'C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/text_files/all_ds_pagetitles.txt2020-03-19 16:49:21'

Please help me with this.

Upvotes: 0

Views: 3158

Answers (2)

wwii
wwii

Reputation: 23743

pathlib makes it easy to manipulate file paths. It may be overkill for a single file but if you are working with a sequence of file paths it can simplify things.

import pathlib,datetime
dt = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
fpath = 'C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/text_files/all_ds_pagetitles.txt'
pp = pathlib.PurePath(fpath)

Easily separate the different parts of the path:

>>> print(pp.parent)
C:\Users\anujp\Desktop\sort\Entity_Resolution_Project\data\text_files
>>> print(pp.stem)
all_ds_pagetitles
>>> print(pp.suffix)
.txt
>>> 

Make a new name and a new path.

>>> newname = f'{pp.stem}-{dt}{pp.suffix}'
>>> pp.with_name(newname)
PureWindowsPath('C:/Users/anujp/Desktop/sort/Entity_Resolution_Project/data/text_files/all_ds_pagetitles-2020-03-19 09-35-57.txt')
>>>

Upvotes: 1

dspencer
dspencer

Reputation: 4461

Windows does not allow colons in file paths since the character is reserved as a separator of the drive label and file path, so you may wish to change your timestamp_string to something like:

filename1 = datetime.now().strftime("%Y-%m-%d %H%M%S")
timestamp_string = str(filename1)

Upvotes: 0

Related Questions