Checking file extension

2019-01-06 09:16发布

I'm working on a certain program and I need to have it do different things if the file in question is a flac file, or an mp3 file. Could I just use this?

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

I'm not sure whether it will work.

EDIT: When I use that, it tells me invalid syntax. So what do I do?

10条回答
疯言疯语
2楼-- · 2019-01-06 09:29

Look at module fnmatch. That will do what you're trying to do.

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file
查看更多
爷、活的狠高调
3楼-- · 2019-01-06 09:37
#!/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'
查看更多
Summer. ? 凉城
4楼-- · 2019-01-06 09:38

Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
查看更多
做个烂人
5楼-- · 2019-01-06 09:42
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
查看更多
SAY GOODBYE
6楼-- · 2019-01-06 09:43

os.path provides many functions for manipulating paths/filenames. (docs)

os.path.splitext takes a path and splits the file extension from the end of it.

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

Gives:

/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!
查看更多
迷人小祖宗
7楼-- · 2019-01-06 09:44

one easy way could be:

import os

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

os.path.splitext(file) will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!

查看更多
登录 后发表回答