pythonfilenamespython-3.9sysdate

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)

Solution

  • 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.