Elija un archivo que comience con una cadena dada


En un directorio tengo muchos archivos, llamados más o menos así:

001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...

En Python, tengo que escribir un código que seleccione del directorio un archivo que comience con una determinada cadena. Por ejemplo, si la cadena es 001_MN_DX, Python selecciona el primer archivo, y así sucesivamente.

¿Cómo puedo hacerlo?

 25
Author: Ry-, 2013-03-09

5 answers

Intente usar os.listdir,os.path.join y os.path.isfile.
En forma larga (con bucles for),

import os
path = 'C:/'
files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i:
        files.append(i)

Código, con listas de comprensiones es

import os
path = 'C:/'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         '001_MN_DX' in i]

Marque aquí para la explicación larga...

 35
Author: pradyunsg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:17
import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]
 38
Author: Marc Laugharn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-09 17:16:59
import os, re
for f in os.listdir('.'):
   if re.match('001_MN_DX', f):
       print f
 6
Author: dawnsong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-09 16:30:56

Puede usar el módulo del sistema operativo para listar los archivos en un directorio.

Eg: Buscar todos los archivos en el directorio actual donde el nombre comienza con 001_MN_DX

import os
list_of_files = os.listdir(os.getcwd()) #list of files in the current directory
for each_file in list_of_files:
    if each_file.startswith('001_MN_DX'):  #since its all type str you can simply use startswith
        print each_file
 3
Author: sansxpz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-09 16:40:44

import os for filename in os.listdir('.'): if filename.startswith('criteria here'): print filename #print the name of the file to make sure it is what you really want. If it's not, review your criteria #Do stuff with that file

 -1
Author: M Gui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-09 17:36:49