检查Python中是否存在*类型的文件

时间:2021-04-16 23:46:00

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 file exists and exit if it doesn't. The code I tried originally is this:

我意识到这看起来与其他关于检查文件是否存在的问题类似,但它是不同的。我想知道如何检查一种类型的文件是否存在,如果不存在就退出。我最初尝试的代码是:

filenames = os.listdir(os.curdir)

for filename in filenames:

   if os.path.isfile(filename) and filename.endswith('.fna'):
        ##do stuff

This works to 'do stuff' to the file that ends in .fna, but I need it to check and make sure the .fna file is there and exit the program entirely if not.

这可以对以.fna结尾的文件进行“处理”,但我需要它检查并确保.fna文件在那里,如果没有,则完全退出程序。

I tried this:

我试着这样的:

try:

    if os.path.isfile(filename) and filename.endswith('.fna'):
        ## Do stuff 
except: 

    sys.stderr.write (‘No database file found. Exiting program. /n’)
    sys.exit(-1)

But that didn't work, it just skips the whole function if the .fna file isn't there, without printing the error.

但这并不奏效,如果。fna文件不存在,它会跳过整个函数,而不会打印错误。

6 个解决方案

#1


9  

The for statement in Python has a little-known else clause:

Python中的for语句有一个鲜为人知的else子句:

for filename in filenames:
    if os.path.isfile(filename) and filename.endswith(".fna"):
        # do stuff
        break
else:
    sys.stderr.write ('No database file found. Exiting program. \n')
    sys.exit(-1)

The else clause is run only if the for statement runs through its whole enumeration without executing the break inside the loop.

只有当for语句在整个枚举中运行而不执行循环中的中断时,才会运行else子句。

#2


7  

Look at the glob module:

查看glob模块:

import glob
import os
import sys

databases = filter(os.path.isfile, glob.glob('./*.fna'))

if not databases:
    sys.stderr.write("No database found.\n\n")
    exit(1)

for database in databases:
    do_something_with(database)

#3


1  

filenames = os.listdir(os.curdir)
found = False
for filename in filenames:
    if os.path.isfile(filename) and filename.endswith('.fna'):
        found = True
if not found:
    sys.stderr.write ('No database file found. Exiting program. \n')
    sys.exit(-1)

#4


0  

If you are using exceptions, do not test to see if the file exists. That's why you're using exceptions to start with.

如果您正在使用异常,不要测试该文件是否存在。这就是为什么要从异常开始。

try:
    # No if statement doing the check
    # Start doing stuff assuming abc.fna exists
except:
    # Uh oh! Something went bad.
    # Display error messages, clean up, carry on

To clarify, consider the code snippet:

要澄清,请考虑代码片段:

try:
    with open('hi.txt') as f:
        print f.readlines()
except:
    print 'There is no hi.txt!'

#5


0  

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

您的try/except块因为os.path而无法工作。isfile失败时不会抛出异常;它仅仅返回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.

for循环的else子句是奇怪的,不直观的。使用break来表示循环是成功的,而不是合法地破坏循环,这很奇怪,而且与Python的哲学相反。

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

#6


0  

Check out os.path.splitext(path) function which says:

函数的作用是:

Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').

将路径名路径分割成一对(根、ext),这样根+ ext ==路径,ext为空,或者从一个周期开始,最多只包含一个周期。基线期被忽略;splitext(。cshrc文件中)返回(“。cshrc’,”)。

Here's an example:

这里有一个例子:

>>> os.path.splitext("./01The News from Lake Wobegon/AlbumArtSmall.jpg")
('./01The News from Lake Wobegon/AlbumArtSmall', '.jpg')
>>> 

#1


9  

The for statement in Python has a little-known else clause:

Python中的for语句有一个鲜为人知的else子句:

for filename in filenames:
    if os.path.isfile(filename) and filename.endswith(".fna"):
        # do stuff
        break
else:
    sys.stderr.write ('No database file found. Exiting program. \n')
    sys.exit(-1)

The else clause is run only if the for statement runs through its whole enumeration without executing the break inside the loop.

只有当for语句在整个枚举中运行而不执行循环中的中断时,才会运行else子句。

#2


7  

Look at the glob module:

查看glob模块:

import glob
import os
import sys

databases = filter(os.path.isfile, glob.glob('./*.fna'))

if not databases:
    sys.stderr.write("No database found.\n\n")
    exit(1)

for database in databases:
    do_something_with(database)

#3


1  

filenames = os.listdir(os.curdir)
found = False
for filename in filenames:
    if os.path.isfile(filename) and filename.endswith('.fna'):
        found = True
if not found:
    sys.stderr.write ('No database file found. Exiting program. \n')
    sys.exit(-1)

#4


0  

If you are using exceptions, do not test to see if the file exists. That's why you're using exceptions to start with.

如果您正在使用异常,不要测试该文件是否存在。这就是为什么要从异常开始。

try:
    # No if statement doing the check
    # Start doing stuff assuming abc.fna exists
except:
    # Uh oh! Something went bad.
    # Display error messages, clean up, carry on

To clarify, consider the code snippet:

要澄清,请考虑代码片段:

try:
    with open('hi.txt') as f:
        print f.readlines()
except:
    print 'There is no hi.txt!'

#5


0  

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

您的try/except块因为os.path而无法工作。isfile失败时不会抛出异常;它仅仅返回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.

for循环的else子句是奇怪的,不直观的。使用break来表示循环是成功的,而不是合法地破坏循环,这很奇怪,而且与Python的哲学相反。

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

#6


0  

Check out os.path.splitext(path) function which says:

函数的作用是:

Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').

将路径名路径分割成一对(根、ext),这样根+ ext ==路径,ext为空,或者从一个周期开始,最多只包含一个周期。基线期被忽略;splitext(。cshrc文件中)返回(“。cshrc’,”)。

Here's an example:

这里有一个例子:

>>> os.path.splitext("./01The News from Lake Wobegon/AlbumArtSmall.jpg")
('./01The News from Lake Wobegon/AlbumArtSmall', '.jpg')
>>>