Copy Files using shutil library

Asked

Viewed 50 times

-4

Hello, I’m learning the programming in Python and a question has arisen regarding the shutil library.

Theoretically, I can make the copy of the file using this library, however, I wonder if there is a way to paste the file in another directory, the name of the file is changed, adding the date of the current day, automatically, to run every day.

To copy the file to the directory in a very rustic way, I make the manual change in the destination, changing its name directly in the code.

I am using the following programming:

from shutil import copy

orig = r 'diretorio1\arquivo.txt'
des = r 'diretorio2\arquivo_(dia_de_hoje).txt' #aqui realizo o preenchimento manual do dia do hoje, e gostaria que essa parte fosse automática.

copy(orig, des)

The result I seek is : file(dia_de_hoje). txt being generated without I need to perform this manual replacement in the code.

  • What happens if in the variable des you set the new file name? Type des = 'diretorio2/novo.txt'

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

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

2 answers

0

Hello, friend. So, there’s a little fancy way to do this data transfer + directory change + file name change. I don’t know if you’ll sympathize, but I’ll put the code here.

Setting the date

There is a much faster way to define the date, using the datetime() function, but I don’t usually use it to have a greater freedom of handling the output. This is how I use:

import time
t = time.localtime ()

dia = t.tm_mday
mês = t.tm_mon

if dia < 10:
    dia = str(0) + str(dia) #Acrescentando o 0 em dias menores que 10
if mês < 10:
    mês = str(0) + str(mês) #Acrescentando o 0 em meses menores que 10
    
ano = t.tm_year

data = str(dia) + str(mês) + str(ano)

Source file and output file

Note: This part of the code assumes that the source file is in the same folder where the code is being executed. To change this, just add the path (path) of the folder, as it was done in "output".

origem = input("Digite o nome do arquivo de origem: ")
arquivo = open(origem + ".txt", "r")
saída = open("/users/HP/" + origem + str(data) + ".txt", "w") #Nome com data. Note que você pode alterar o path para o que deseja. Este "/users/HP/" é apenas um exemplo.

Writing in the new file

for linha in arquivo.readlines():
    palavra = linha
    saída.write(palavra)

saída.close()

Complete code

import time
t = time.localtime ()

dia = t.tm_mday
mês = t.tm_mon

if dia < 10:
    dia = str(0) + str(dia)
if mês < 10:
    mês = str(0) + str(mês)
    
ano = t.tm_year

data = str(dia) + str(mês) + str(ano)

origem = input("Digite o nome do arquivo de origem: ")
arquivo = open(origem + ".txt", "r")
saída = open("/users/HP/" + origem + str(data) + ".txt", "w")

for linha in arquivo.readlines():
    palavra = linha
    saída.write(palavra)

saída.close()

Finally, just look for the new file in the directory you have chosen. I hope you were able to help. Good luck!

0

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:

  1. Import required libraries;
  2. Capture and treat the current date;
  3. Capture the file source path;
  4. Enter the full name of the desired file;
  5. Capture the destination path;
  6. 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.

Browser other questions tagged

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