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

Asked

Viewed 65 times

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

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

Would anyone know how to solve this question?

Note: the first url is from a network folder, so I deleted the start to
facilitate reading.

1 answer

1


Just use the method date.today() module datetime to pick up the current date and use the date formatting options to correctly create the file name 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 code working

In the above example I am 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 the pyformat.org with a cheatsheet for python formatting.


With the above information you already have enough tools to solve your problem. You will get 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.