Check if a directory contains a file with a given extension

后端 未结 3 910
梦毁少年i
梦毁少年i 2020-12-29 21:58

I need to check the current directory and see if a file with an extension exists. My setup will (usually) only have one file with this extension. I need to check if that fil

相关标签:
3条回答
  • 2020-12-29 22:38

    If you only want to check that any file ends with a particular extension, use any.

    import os
    if any(File.endswith(".true") for File in os.listdir(".")):
        print("true")
    else:
        print("false")
    
    0 讨论(0)
  • 2020-12-29 22:38

    You should use the glob module to look for exactly the files that you're interested in:

    import glob
    
    fileList = glob.glob("*.true")
    for trueFile in fileList:
        doSomethingWithFile(trueFile)
    
    0 讨论(0)
  • 2020-12-29 22:48

    You can use the else block of the for:

    for fname in os.listdir('.'):
        if fname.endswith('.true'):
            # do stuff on the file
            break
    else:
        # do stuff if a file .true doesn't exist.
    

    The else attached to a for will be run whenever the break inside the loop is not executed. If you think a for loop as a way to search something, then break tells whether you have found that something. The else is run when you didn't found what you were searching for.

    Alternatively:

    if not any(fname.endswith('.true') for fname in os.listdir('.')):
        # do stuff if a file .true doesn't exist
    

    Moreover you could use the glob module instead of listdir:

    import glob
    # stuff
    if not glob.glob('*.true')`:
        # do stuff if no file ending in .true exists
    
    0 讨论(0)
提交回复
热议问题