检查Python中是否存在GZIP文件 [英] Check if GZIP file exists in Python

查看:230
本文介绍了检查Python中是否存在GZIP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行Python的同时检查Linux计算机上是否存在.gz文件.如果我对一个文本文件执行此操作,则以下代码有效:

I would like to check for the existence of a .gz file on my linux machine while running Python. If I do this for a text file, the following code works:

import os.path
os.path.isfile('bob.asc')

但是,如果bob.asc为gzip格式(bob.asc.gz),Python将无法识别它.理想情况下,我想使用os.path.isfile或非常简洁的东西(无需编写新函数).是否可以通过Python或通过更改系统配置来使文件可识别?

However, if bob.asc is in gzip format (bob.asc.gz), Python does not recognize it. Ideally, I would like to use os.path.isfile or something very concise (without writing new functions). Is it possible to make the file recognizable either in Python or by changing something in my system configuration?

很遗憾,我不能更改数据格式或文件名,因为它们是由公司批量提供给我的.

Unfortunately I can't change the data format or the file names as they are being given to me in batch by a corporation.

推荐答案

当然不是;它们是完全不同的文件.您需要单独测试:

Of course it doesn't; they are completely different files. You need to test it separately:

os.path.isfile('bob.asc.gz')

如果当前工作目录中存在该文件,则将返回True.

This would return True if that exact file was present in the current working directory.

一种解决方法可能是:

from os import listdir, getcwd
from os.path import splitext, basename

any(splitext(basename(f))[0] == 'bob.asc' for f in listdir(getcwd()))

这篇关于检查Python中是否存在GZIP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆