我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?
if m == *.mp3
...
elif m == *.flac
...
我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?
if m == *.mp3
...
elif m == *.flac
...
当前回答
查看模块fnmatch。它会达到你想要的效果。
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
其他回答
假设m是一个字符串,你可以使用endswith:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
不区分大小写,并消除可能较大的else-if链:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
如果你的文件上传了
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
我很惊讶没有一个答案建议使用pathlib库。
当然,它的使用是视情况而定的,但当涉及到文件处理或统计pathlib是黄金。
下面是一个片段:
import pathlib
def get_parts(p: str or pathlib.Path) -> None:
p_ = pathlib.Path(p).expanduser().resolve()
print(p_)
print(f"file name: {p_.name}")
print(f"file extension: {p_.suffix}")
print(f"file extensions: {p_.suffixes}\n")
if __name__ == '__main__':
file_path = 'conf/conf.yml'
arch_file_path = 'export/lib.tar.gz'
get_parts(p=file_path)
get_parts(p=arch_file_path)
输出:
/Users/hamster/temp/src/pro1/conf/conf.yml
file name: conf.yml
file extension: .yml
file extensions: ['.yml']
/Users/hamster/temp/src/pro1/conf/lib.tar.gz
file name: lib.tar.gz
file extension: .gz
file extensions: ['.tar', '.gz']
或者:
from glob import glob
...
for files in glob('path/*.mp3'):
do something
for files in glob('path/*.flac'):
do something else
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"