Check that a *type* of file exists in Python

后端 未结 6 697
囚心锁ツ
囚心锁ツ 2021-01-11 17:03

I realize this looks similar to other questions about checking if a file exists, but it is different. I\'m trying to figure out how to check that a type of

6条回答
  •  一向
    一向 (楼主)
    2021-01-11 17:19

    Your try/except block didn't work because os.path.isfile does not throw an exception if it fails; it merely returns False.

    else clauses for for loops are weird and non-intuitive. Using break to signify that the loop was successful rather than legitimately breaking it is just weird, and contrary to Python's philosophy.

    Here's a nice, Pythonic way of doing what you want:

    want = lambda f: os.path.isfile(f) and f.endswith(".fna")
    valid_files = [f for f in os.listdir(os.curdir) if want(f)]
    if len(valid_files) == 0:
        print >>sys.stderr, "failed to find .fna files!"
        sys.exit(1)
    for filename in valid_files:
        # do stuff
    

提交回复
热议问题