파일의 확장자를 어떻게 확인할 수 있습니까?
파일 확장자에 따라 다른 작업을 수행 해야하는 특정 프로그램을 만들고 있습니다. 이걸 사용해도 될까요?
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
'Programing' 카테고리의 다른 글
Github Pages에서 HTTP 404를 수정하는 방법? (0) | 2020.06.28 |
---|---|
숫자에서 중요하지 않은 후행 0을 제거 하시겠습니까? (0) | 2020.06.28 |
최소 신장이있는 부모 내부의 자녀 : 100 % 상속받지 않음 (0) | 2020.06.28 |
작성기 경고 : openssl 확장이 없습니다. (0) | 2020.06.28 |
iPhone TableView 셀에서 셀의 오른쪽에 작은 화살표 추가 (0) | 2020.06.28 |