How to provide date with specific format in folder path in Python

I received csv file with sysdate attached to the filename with format yyyy-mm-dd. For example today i received file as User_test_2023-10-20.csv.

I have below python code where i want to attach this sysdate with format yyyy-md-dd to the filename but not sure how to do this.

import codecs
import shutil

with codecs.open(r"C:\User_test_.csv", encoding="utf-16") as input_file:
    with codecs.open(r"C:\User_test_.csv", "w", encoding="utf-8") as output_file:
        shutil.copyfileobj(input_file, output_file)

  • Do you mean that you are trying to access the file based on the current date in sysdate?

    – 

  • yes it should be sysdate with format yyyy-mm-dd

    – 

import pathlib
from datetime import datetime

current_date = datetime.now().strftime("%Y-%m-%d")

path = pathlib.Path(f'C:/User_test_{current_date}.csv')
print(path)

Output:

C:/User_test_2023-10-20.cs

I will add though:

with codecs.open(path, encoding="utf-16") as input_file:
    with codecs.open(path, "w", encoding="utf-8") as output_file:
        shutil.copyfileobj(input_file, output_file)

Since it seems you want to change the encoding:

with path.open("r", encoding="utf-16") as in_file:
    content = in_file.read()
    with path .open("w", encoding="utf-8") as out_file:
        out_file.write(content)

Which I’m not sure if it’ll work, you whould use different filenames or close one file before overwriting it:

import pathlib
from datetime import datetime

current_date = datetime.now().strftime("%Y-%m-%d")

path = pathlib.Path(f'C:/User_test_{current_date}.csv')

with path.open("r", encoding="utf-16") as in_file:
    content = in_file.read()

with path.open("w", encoding="utf-8") as out_file:
    out_file.write(content)

Note: If you didn’t need to change encoding you could use .seek(0) and .truncate() to read and write in a single opening of the file.

We can use datetime module to get the date in this exact format and then just concatenate the strings, this can be done with an f raw string to simplify both the joining and the backslashes of the filename.

from datetime import date
today = str(date.today())
filename = fr'C:\User_test_{today}.csv'

Leave a Comment