How to copy a .txt file that updates the name daily - Python

0

I need to copy a TXT file daily from one folder to another, but the file is renamed according to the date, the end after the "_"
always changes with the date value.

Ex: _20181205.txt , _20181206.txt , _20190101.txt .

Below is the code where I left off.

shutil.copy('/8.Relatórios/03. SAM/01_TemposMédios_20181205.txt','C:/Users/br0151338587/Desktop/laboratorioPython')

Would anyone know how I can resolve this?

Note: the 1st url is from a network folder, then I deleted the start for
make reading easier.

    
asked by anonymous 05.12.2018 / 14:03

1 answer

1

Just use the date.today() method of the datetime to get the current date and use date formatting options to create it correctly the name of the file you want. For example:

from datetime import date

hoje = date.today()
arquivo = f"01_TemposMédios_{hoje:%Y%m%d}.txt"

print(arquivo)  # '01_TemposMédios_20191205.txt'

Repl.it with the working code

In the example above I'm using string interpolation with f-strings ( PEP 498 implemented in Python 3.6+), but you can use str.format() " if you prefer.

arquivo = "01_TemposMédios_{0:%Y%m%d}.txt".format(hoje)

You can use pyformat.org with a cheatsheet for python formatting.

With the above information you already have enough tools to solve your problem. You'll get a code like this:

from shutil import copy
from datetime import date

hoje = date.today()
arquivo_origem = f"/8.Relatórios/03. SAM/01_TemposMédios_{hoje:%Y%m%d}.txt"
arquivo_destino = "C:/Users/br0151338587/Desktop/laboratorioPython"

copy(arquivo_origem, arquivo_destino)
    
05.12.2018 / 14:42