파일 확장자는 어떻게 확인할 수 있나요?
파일 확장자에 따라 다른 작업을 해야 하는 프로그램을 만들고 있습니다.이거 써도 돼요?
if m == *.mp3
...
elif m == *.flac
...
가정하다m
문자열입니다.endswith
:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
대소문자를 구분하지 않고 잠재적으로 대규모 체인을 배제하기 위해:
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입니다! 폴더 1/폴더/사운드 파일flac은 flac 파일입니다!
사용하다pathlib
Python 3.4 이후.
from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
모듈 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)
는 2개의 값(확장자가 없는 파일명+확장자만)의 태플을 반환합니다.따라서 두 번째 인덱스([1)는 확장자만 제공합니다.멋진 점은 이 방법으로 필요에 따라 파일 이름에도 쉽게 접근할 수 있다는 것입니다!
오래된 이야기지만, 미래의 독자들에게 도움이 될 수도 있다...
다른 이유 없이 코드를 보다 독립적인 플랫폼으로 만들기 위해서라도 파일 이름에 .lower()를 사용하지 않도록 하겠습니다.(linux는 대소문자를 구분합니다.파일명의 .lower()는 반드시 로직을 손상시킵니다.혹은 중요한 파일입니다!)
왜 re를 사용하지 않는가? (더 견고해지려면 각 파일의 매직 파일 헤더를 확인해야 한다...)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))
출력:
myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
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
확장자를 확인하기 전에 "파일"이 실제로 폴더가 아닌지 확인해야 합니다.위의 답변 중 일부는 마침표가 있는 폴더 이름을 고려하지 않습니다.(folder.mp3
유효한 폴더 이름입니다).
파일 확장자 확인:
import os
file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() == ".mp3":
print("It's an mp3")
if file_extension.lower() == ".flac":
print("It's a flac")
출력:
It's an mp3
폴더의 모든 파일 확장자 확인:
import os
directory = "C:/folder"
for file in os.listdir(directory):
file_path = os.path.join(directory, file)
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
print(file, "ends in", file_extension)
출력:
abc.txt ends in .txt
file.mp3 ends in .mp3
song.flac ends in .flac
파일 확장자를 여러 형식과 비교:
import os
file_path = "C:/folder/file.mp3"
if os.path.isfile(file_path):
file_extension = os.path.splitext(file_path)[1]
if file_extension.lower() in {'.mp3', '.flac', '.ogg'}:
print("It's a music file")
elif file_extension.lower() in {'.jpg', '.jpeg', '.png'}:
print("It's an image file")
출력:
It's a music file
#!/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'
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"
파일이 업로드된 경우
import os
file= request.FILES['your_file_name'] #Your input file_name for your_file_name
ext = os.path.splitext(file.name)[-1].lower()
if ext=='.mp3':
#do something
elif ext=='.xls' or '.xlsx' or '.csv':
#do something
else:
#The uploaded file is not the required format
file='test.xlsx'
if file.endswith('.csv'):
print('file is CSV')
elif file.endswith('.xlsx'):
print('file is excel')
else:
print('none of them')
언급URL : https://stackoverflow.com/questions/5899497/how-can-i-check-the-extension-of-a-file
'itsource' 카테고리의 다른 글
PHP에서 시간대를 지정하여 현재 날짜를 가져오시겠습니까? (0) | 2022.11.14 |
---|---|
Larabel 5 – URL에서 공개 삭제 (0) | 2022.11.14 |
RegExp를 사용하는 문자열에서 SQL 추출 패턴 (0) | 2022.11.14 |
in_array 다중값 (0) | 2022.11.14 |
MySQL에서 사용 가능한 다음 ID 찾기 (0) | 2022.11.14 |