【问题标题】:How can I check the extension of a file?如何检查文件的扩展名?
【发布时间】:2011-08-19 11:04:03
【问题描述】:

我正在开发某个程序,我需要根据文件的扩展名做不同的事情。我可以用这个吗?

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

【问题讨论】:

  • 使用python re模块(正则表达式)进行匹配

标签: python file-extension


【解决方案1】:

如果您的文件已上传,那么

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:
      file='test.xlsx'
      if file.endswith('.csv'):
          print('file is CSV')
      elif file.endswith('.xlsx'):
          print('file is excel')
      else:
          print('none of them')
      

      【讨论】:

      【解决方案4】:

      假设m是一个字符串,可以使用endswith

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

      不区分大小写,并消除可能较大的 else-if 链:

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

      【讨论】:

      • ext = m.rpartition('.')[-1];如果 ext == 会更有效率
      • @volcano 为什么不使用.split('.')[-1]?还是rpartition真的效率高?
      • @Stevoisiak,我认为您的评论放错了位置,因为即使您指出这种解决方案也有效
      • 这不考虑带有句点的文件夹名称。 C:/folder.jpg 是有效路径。可以用os.path.isfile(m)确认是文件还是文件夹
      • @JayTuma 感谢您指出这一点,我修正了我的评论
      【解决方案5】:

      从 Python3.4 开始使用pathlib

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

      【讨论】:

      • 这不考虑带有句点的文件夹名称。 (C:/folder.jpg/file.mp3 是有效路径)。
      • @Stevoisiak 你是什么意思?在什么情况下它不能解释这一点?我刚试过,.suffix 正确返回'.mp3'
      • 如果有一个名为folder.mp3的文件夹,上面的代码会认为该文件夹是一个mp3文件。
      • @Stevoisiak return Path('your_folder.mp3').is_file() and Path('your_folder.mp3').suffix == '.mp3'
      【解决方案6】:

      一个旧线程,但可能对未来的读者有所帮助......

      我会避免在文件名上使用 .lower(),除非是为了让您的代码更加独立于平台。 (linux 区分大小写的,文件名上的 .lower() 肯定会最终破坏你的逻辑......或者更糟糕的是,一个重要的文件!)

      为什么不使用 re? (虽然为了更加健壮,你应该检查每个文件的魔法文件头...... 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)) 
      

      输出:

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

      【讨论】:

        【解决方案7】:
        if (file.split(".")[1] == "mp3"):
            print "its mp3"
        elif (file.split(".")[1] == "flac"):
            print "its flac"
        else:
            print "not compat"
        

        【讨论】:

        • 这不适用于包含多个.s 的文件,例如some.test.file.mp3
        • 你可以做 [-1] 来捕捉那个边缘情况。
        【解决方案8】:

        一种简单的方法可能是:

        import os
        
        if os.path.splitext(file)[1] == ".mp3":
            # do something
        

        os.path.splitext(file) 将返回一个包含两个值的元组(没有扩展名的文件名 + 只是扩展名)。因此,第二个索引 ([1]) 将为您提供扩展名。很酷的是,如果需要,您还可以通过这种方式轻松访问文件名!

        【讨论】:

          【解决方案9】:
          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
          

          【讨论】:

            【解决方案10】:
            #!/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'
            

            【讨论】:

              【解决方案11】:

              或者也许:

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

              【讨论】:

                【解决方案12】:

                os.path 提供了许多用于操作路径/文件名的函数。 (docs)

                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 文件!

                【讨论】:

                • 此方法忽略前导句点,因此/.mp3 不被视为 mp3 文件。然而,这是处理前导空格的方式。例如.gitignore 不是文件格式
                • 这不考虑带有句点的文件夹名称。 (C:/folder.jpg/file.mp3 是有效路径)。你可以排除那些os.path.isfile(m)
                【解决方案13】:

                查看模块 fnmatch。这会做你想做的事。

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

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 1970-01-01
                  • 2014-11-08
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-06-21
                  • 1970-01-01
                  • 2019-04-22
                  • 2011-04-25
                  相关资源
                  最近更新 更多