Programing

파일의 확장자를 어떻게 확인할 수 있습니까?

lottogame 2020. 6. 28. 18:28
반응형

파일의 확장자를 어떻게 확인할 수 있습니까?


파일 확장자에 따라 다른 작업을 수행 해야하는 특정 프로그램을 만들고 있습니다. 이걸 사용해도 될까요?

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

m문자열 이라고 가정하면 다음을 사용할 수 있습니다 endswith.

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

대소 문자를 구분하지 않고 잠재적으로 큰 else-if 체인을 제거하려면 다음을 수행하십시오.

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

os.path경로 / 파일 이름 조작을위한 많은 기능을 제공합니다. ( 문서 )

os.path.splitext 경로를 가져 와서 파일 확장자를 끝에서 분리합니다.

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

제공합니다 :

/folder/soundfile.mp3는 mp3입니다!
folder1 / folder / soundfile.flac는 flac 파일입니다!

모듈 fnmatch를보십시오. 그것은 당신이하려는 일을 할 것입니다.

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file

또는 아마도 :

from glob import glob
...
for files in glob('path/*.mp3'): 
  do something
for files in glob('path/*.flac'): 
  do something else

한 가지 쉬운 방법은 다음과 같습니다.

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!


Use pathlib From Python3.4 onwards.

from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'

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

if (file.split(".")[1] == "mp3"):
    print "its mp3"
elif (file.split(".")[1] == "flac"):
    print "its flac"
else:
    print "not compat"

An old thread, but may help future readers...

I would avoid using .lower() on filenames if for no other reason than to make your code more platform independent. (linux is case sensistive, .lower() on a filename will surely corrupt your logic eventually ...or worse, an important file!)

Why not use re? (Although to be even more robust, you should check the magic file header of each file... How to check type of files without extensions in 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)) 

Output:

myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac

#!/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'

import pandas as pd
file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('non of them')

참고URL : https://stackoverflow.com/questions/5899497/how-can-i-check-the-extension-of-a-file

반응형