I understand you are trying to implement a code that is able to copy a file from one directory to another by renaming so that the new name contains the old name, plus the character of "_", plus the current date of the system in YYYYYYMMDD mode, plus extension.
OBSERVATION:
The file extension is very important. Because, the file can only be manipulated if it has a valid extension.
To implement a decent code we must pay attention to the following logic:
- Import required libraries;
- Capture and treat the current date;
- Capture the file source path;
- Enter the full name of the desired file;
- Capture the destination path;
- Copy and rename the file.
Well, following this logic we can implement the following code:
from os import chdir, listdir, rename
from shutil import copy
from os.path import isfile
import time
t = time.localtime()
t1, t2, t3 = f'{t[0]}', f'{t[1]:02}', f'{t[2]:02}'
cam = input('Informe o caminho arquivo: ')
chdir(cam)
for i in listdir():
if isfile(i):
print(i)
nome = input('Informe o nome completo do arquivo desejado: ')
cam2 = input('Informe o caminho destino: ')
copy(nome, cam2)
chdir(cam2)
for j in listdir():
if isfile(j) and j == nome:
rename(nome, nome[:-4] + '_' + t1 + t2 + t3 + nome[-4:])
Note that the first thing in the code is the import of the required libraries and methods. It is then captured and treated to the current date. Yeah, the method time localtime.() returns us a tuple containing 9 parameters, among the wanted, sevemos care only with the first three, which provides us, respectively, the information of year, month and day. So we have t[0] = year, t[1] = month and t[2] = day.
Following the logic, the code will ask us the path to the source directory of the file. This path is obviously the path of the folder that contains the file, which we want to copy it.
After we inform the file path, the code focuses on the specified path and the first block for will go through the specified folder, listing all files from that folder.
At this point we must choose and enter the full name - name + extension - of the desired file. Subsequently, we must inform the path of the destination directory.
Then the code copies the file to the destination folder and then renames it.
What happens if in the variable
des
you set the new file name? Typedes = 'diretorio2/novo.txt'
– Woss
Thank you for your reply. The file is renamed, but in this case the replacement is manual.I would like to know if there is a way that this file is copied every day only with the date of the current day so that it is not necessary to manually fill in the date of the day.
– Henrique
Use the library
datetime
to get the current date, set the file name using it and then configure a scheduled task on your system to run the code every day.– Woss