Rename a file with Python

1

I'm trying to change the name of a file using Python but the name does not change. The program has to take a photo, save it, copy it to a server, change the name of the copied photo and change the name of the original photo. So, first, I define a variable that is going to be an exact date and time. After that, I take a photo and save it as image.jpg Next, I copy image.jpg to another route (server path), and I try to change its name using the variable I defined earlier (which is the hors and current date ). But the name does not change and the file is deleted. After that I change the name of the original photo with the same function and the name is changed .... I do not know why the copied photo does not change its name. Here is the code:

import picamera
import os
import shutil
fecha = time.strftime("%c")  # En esta variable se guarda la fecha actual y la hora para renombrar la foto guardada          
camera.capture('/home/pi/Desktop/RaspAlarm/imagen.jpg')
print("Capturando foto")
time.sleep(5)
print("Copiando foto al servidor")
shutil.copy("/home/pi/Desktop/RaspAlarm/imagen.jpg", "/var/www/html/RaspAlarm/Fotos")
time.sleep(1)
os.listdir("/var/www/html/RaspAlarm/Fotos")
os.rename ("/var/www/html/RaspAlarm/Fotos/imagen.jpg", fecha)
print("Cambiando nombre al archivo")
os.rename ("/home/pi/Desktop/RaspAlarm/imagen.jpg", fecha)
time.sleep(1)
print("Foto guardada")

Could someone help me? Thanks

    
asked by Sergio Muñoz 08.05.2017 в 16:54
source

2 answers

1

The simple solution is to do what @GermanAlzate proposes in your comment (create the image with the appropriate name from the beginning and not rename afterwards).

The object of the answer is to explain why os.rename works with the file located in the work path and not with the one that copies in the external path.

To be able to rename the file it is obligatory to provide the complete path in the original name as well as in the exit name or to be in the same working directory as the file :

os.rename("/var/www/html/RaspAlarm/Fotos/imagen.jpg", "/var/www/html/RaspAlarm/Fotos/{}.jpg".format(fecha))

Another option is to change the working directory previously with:

os.chdir('/var/www/html/RaspAlarm/Fotos')
os.rename ("imagen.jpg", "{}.jpg".format(fecha))

In the case of the original photo, there is no problem because you are in the same working directory as the script, in fact it is not necessary to provide the complete path (as if you used os.chdir in the previous case):

os.rename ("imagen.jpg", '{}.jpg'.format(fecha))

The correct code would be:

import picamera
import os
import shutil

fecha = time.strftime("%c")  # En esta variable se guarda la fecha actual y la hora para renombrar la foto guardada          
camera.capture('/home/pi/Desktop/RaspAlarm/imagen.jpg')
print("Capturando foto")
time.sleep(5)
print("Copiando foto al servidor")
shutil.copy("/home/pi/Desktop/RaspAlarm/imagen.jpg", "/var/www/html/RaspAlarm/Fotos")
time.sleep(1)
os.rename ("/var/www/html/RaspAlarm/Fotos/imagen.jpg","var/www/html/RaspAlarm/Fotos/{}.jpg".format(fecha))
print("Cambiando nombre al archivo")
os.rename ("imagen.jpg", "{}.jpg".format(fecha))
time.sleep(1)
print("Foto guardada")

I repeat that this is just in case someone encounters the same problem when using os.rename , the logical thing in your case is to create the first file using fecha as a name.

Edit:

str.format () works through "replacement fields" that are denoted with braces {}. Anything that is not contained in braces is considered literal text, which is copied without changes in the output. You can use the number you want of replacements in the same chain. You can pass strings or variables (including integers, floats ...), operations, function calls, etc:

c = 'mi cumpleaños'
cadena = 'La fecha de {} es el {} de {}.'.format(c, 20+1, 'Enero')
print(cadena)

Exit:

  

The date of my birthday is January 21.

The substitution is made according to the order in which the arguments are given, although it can be specified using indices within {} :

cadena1 = 'Mi color preferido es el {0}, el tuyo el {1}'.format('azul', 'blanco')
cadena2 = 'Mi color preferido es el {1}, el tuyo el {0}'.format('azul', 'blanco')
print(cadena1)
print(cadena2)

Exit:

  

My favorite color is blue, yours is white
  My favorite color is white, yours is blue

This is the basics, it allows more interesting things like text alignment, alignment and rounding of floats, etc. These utilities are a great help, for example, to create tabulated data outputs on the screen.

If you use Python 3.6 or superiros there are also the so-called literals of chain that work in a similar way but simplify it further by following Python's 'understandable for humans' philosophy and allowing 'magic' to be done XD:

import datetime
import locale
locale.setlocale(locale.LC_TIME, '')

nombre = 'Andrómeda'
edad = 27
nacimiento = datetime.date(1990, 10, 12)

cadena = f'Mi nombre es {nombre}, mi edad el año que viene es {edad+1} y mi fecha de nacimiento es el{nacimiento: %A %d de %B de %Y}.'
print(cadena)

Exit:

  

My name is Andromeda, my age next year is 28 and my date of birth is Friday October 12, 1990.

    
answered by 08.05.2017 / 18:16
source
1

First, on certain operating systems (read Windows primarily) you are creating an invalid file name ( fecha ).

import time
fecha = time.strftime("%c")
print(fecha)

What ultimately happens is that you end up trying to create a file that would be called for example Mon May 8 16:35:57 2017 , the spaces, letters and numbers may be valid, but : no. I suggest you always paste the full text of the error, but it is more difficult to make a diagnosis.

For starters I would better name the file, something like this:

import time
fecha = time.strftime("%Y%m%d-%H%M%S")
print(fecha)

Which would give us a more compatible name, for example: 20170508-165022 and it would be logical to do as you already commented something like this to finish building the filename:

os.rename ("imagen.jpg", "{}.jpg".format(fecha))

But be careful, as he said @FJSevilla, this rename that you are doing assumes as a source file, one that is in the execution path of the Python Script, you should change the current directory to the desired or use the full path of the files.

    
answered by 08.05.2017 в 18:59