[pyar] [Bulk] Generar nombres de archivos diferentes en base a uno ya existente

Miguel Scapolla mascapolla en yahoo.com.ar
Dom Oct 5 10:46:23 ART 2014


On Sat, 4 Oct 2014 23:00:39 -0300
Tomas Delvechio <tomasdelvechio en yahoo.com.ar> wrote:

> El problema obvio es que hay nombres que se pueden repetir y tengo que
> armar un nuevo nombre (Esto puede ocurrir un numero de veces
> indeterminado).

Si el orden no importa (que foo.txt sea el primero, foo.txt-0 el segundo y así), podés usar mkstemp [0] para generar un nombre de archivo único. Tené en cuenta que mkstemp devuelve una tupla con el handle del archivo abierto y el nombre absoluto, no te olvides de cerrar ese handle [1]. También, tené en cuenta que crea el archivo en disco con tamaño 0 y permisos 0600.

>>> import os
>>> import tempfile

>>> nombre_archivo = 'readme.txt'
>>> (archbas, archext) = os.path.splitext(nombre_archivo)
>>> (fh, nombre_archivo) = tempfile.mkstemp(dir='./', prefix=archbas.replace('.', '-') + '-', suffix=archext)
>>> os.close(fh)
>>> nombre_archivo
'/home/usuario/pruebas/readme-Wo6MJc.txt'
>>> 

>>> nombre_archivo = 'archivo.multi.ext.txt'
>>> (archbas, archext) = os.path.splitext(nombre_archivo)
>>> (fh, nombre_archivo) = tempfile.mkstemp(dir='./', prefix=archbas.replace('.', '-') + '-', suffix=archext)
>>> os.close(fh)
>>> nombre_archivo
'/home/usuario/pruebas/archivo-multi-ext-GEy34C.txt'
>>> 


Slds.

[0]: https://docs.python.org/2/library/tempfile.html#tempfile.mkstemp
[1]: http://www.logilab.org/blogentry/17873

-- 

---------------------------------------------------------------------
Miguel Scapolla.
Free the Mallocs!
---------------------------------------------------------------------



More information about the pyar mailing list