我在一个特定的程序上工作,我需要根据文件的扩展名做不同的事情。我能用这个吗?

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

当前回答

如果你的文件上传了

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

其他回答

假设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

在检查扩展名之前,您应该确保“文件”实际上不是一个文件夹。上面的一些答案没有说明带句点的文件夹名称。(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

查看模块fnmatch。它会达到你想要的效果。

import fnmatch
import os

for file in os.listdir('.'):
    if fnmatch.fnmatch(file, '*.txt'):
        print file
file='test.xlsx'
if file.endswith('.csv'):
    print('file is CSV')
elif file.endswith('.xlsx'):
    print('file is excel')
else:
    print('none of them')