python 如果文件不存在则失败

1 投票
4 回答
13911 浏览
提问于 2025-04-17 02:19

我有一个循环,它会检查文件夹里是否有 *.zip 文件。

for file in glob.glob( os.path.join(rootdir, '*.zip')):
        print "zip", file
        #Check if file does not exist
        if not os.path.exists(file):
            print "No files"
            #return
        else:
            some code

现在如果文件存在,其他的操作就会进行,但如果没有 zip 文件,就不会打印任何内容。

有什么建议吗?谢谢!

4 个回答

1

如果没有文件存在,那么你的循环根本不会执行。测试 os.path.exists(file) 这个条件总是会返回真(除非在你运行循环的时候,有其他程序在删除文件),因为如果没有文件,glob 就不会把它列为一个文件。

files = glob.glob( os.path.join(rootdir, '*.zip'))
for file in files:
        print "zip", file
if len(files) == 0:
        print "no files"
3

如果没有压缩文件(zip文件),那么你就是在对一个空的列表进行循环。你可以试试下面这样的写法:

files = glob.glob( os.path.join(rootdir, '*.zip'))
if len(files) != 0:
    for file in files:
        print "zip", file
        #Check if file does not exist
        if not os.path.exists(file):
            print file, "does not exist"
            #return
        else:
            some code
else:
    print "No files"
3

如果那个文件夹里没有压缩文件,for循环就不会执行。

就像

for i in []:
    print "Hello"

因为没有可以遍历的元素,所以什么都不会打印出来。

如果你需要那个错误信息,可以这样做:

filelist = glob.glob(os.path.join(rootdir, '*.zip'))
if filelist:
    for f in filelist:
        # some code
else:
    print "No files"

撰写回答