0

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.

2 Answers 2

1

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')
>>>
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

for the love of god NEVER EVER EVER HAVE A SPACE IN A FILENAME.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.