Comprobación de la extensión de archivo


Estoy trabajando en cierto programa y necesito que haga cosas diferentes si el archivo en cuestión es un archivo flac o un archivo mp3. ¿Puedo usar esto?

if m == *.mp3
   ....
elif m == *.flac
   ....

No estoy seguro de si funcionará.

EDITAR: Cuando uso eso, me dice sintaxis inválida. Entonces, ¿qué hago?

Author: Acorn, 2011-05-05

10 answers

Asumiendo que m es una cadena, puedes usar endswith:

if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...

Para ser insensible a mayúsculas y minúsculas, y para eliminar una cadena potencialmente grande else-if:

m.lower().endswith(('.png', '.jpg', '.jpeg'))

(Gracias a Wilhem Murdoch por la lista de args a endswith)

 223
Author: lafras,
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
2015-09-17 19:39:53

os.path proporciona muchas funciones para manipular rutas/nombres de archivo. (docs )

os.path.splitext toma una ruta y divide la extensión del archivo desde el final de la misma.

import os

filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]

for fp in filepaths:
    # Split the extension from the path and normalise it to lowercase.
    ext = os.path.splitext(fp)[-1].lower()

    # Now we can simply use == to check for equality, no need for wildcards.
    if ext == ".mp3":
        print fp, "is an mp3!"
    elif ext == ".flac":
        print fp, "is a flac file!"
    else:
        print fp, "is an unknown file format."

Da:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!
 40
Author: Acorn,
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
2011-05-05 15:51:07

Mira el módulo fnmatch. Eso hará lo que estás tratando de hacer.

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file
 9
Author: John Gaines Jr.,
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
2011-05-05 15:03:35

O tal vez:

from glob import glob
...
for files in glob('path/*.mp3'): 
  do something
for files in glob('path/*.flac'): 
  do something else
 3
Author: phynfo,
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
2014-01-06 16:54:11

Una manera fácil podría ser:

import os

if os.path.splitext(file)[1] == ".mp3":
    # do something

os.path.splitext(file) devolverá una tupla con dos valores (el nombre del archivo sin extensión + solo la extensión). El segundo índice ([1]) por lo tanto le dará solo la extensión. Lo bueno es, que de esta manera también puede acceder al nombre del archivo con bastante facilidad, si es necesario!

 2
Author: upgrd,
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-03-07 09:11:18
import os
source = ['test_sound.flac','ts.mp3']

for files in source:
   fileName,fileExtension = os.path.splitext(files)
   print fileExtension   # Print File Extensions
   print fileName   # It print file name
 1
Author: Rajan Mandanka,
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
2016-05-17 10:42:01
if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"
 1
Author: Christian Papathanasiou,
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-07-19 07:27:57
#!/usr/bin/python

import shutil, os

source = ['test_sound.flac','ts.mp3']

for files in source:
  fileName,fileExtension = os.path.splitext(files)

  if fileExtension==".flac" :
    print 'This file is flac file %s' %files
  elif  fileExtension==".mp3":
    print 'This file is mp3 file %s' %files
  else:
    print 'Format is not valid'
 0
Author: nprak,
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
2015-02-11 05:29:27

Un hilo viejo, pero puede ayudar a futuros lectores...

Yo evitaría usar .lower () en los nombres de archivo si no es por otra razón que hacer que su código sea más independiente de la plataforma. (linux es sensible a mayúsculas, .lower () en un nombre de archivo seguramente corromperá tu lógica eventualmente ...o peor, un archivo importante!)

¿por Qué no usar re? (Aunque para ser aún más robusto, debe comprobar el encabezado del archivo mágico de cada archivo... Cómo comprobar el tipo de archivos sin extensiones en python? )

import re

def checkext(fname):   
    if re.search('\.mp3$',fname,flags=re.IGNORECASE):
        return('mp3')
    if re.search('\.flac$',fname,flags=re.IGNORECASE):
        return('flac')
    return('skip')

flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
     'myfile.Mov','myfile.fLaC']

for f in flist:
    print "{} ==> {}".format(f,checkext(f)) 

Salida:

myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
 0
Author: Dan F.,
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-12-15 07:58:10

Use pathlib Desde Python3.4 en adelante.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
 0
Author: Greg,
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-06-11 05:31:38