Check if GZIP file exists in Python

拟墨画扇 提交于 2019-12-25 03:14:18

问题


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')

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.


回答1:


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

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

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

Although a workaround could be:

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

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



回答2:


You need to test each file. For example :

if any(map(os.path.isfile, ['bob.asc', 'bob.asc.gz'])):
    print 'yay'



回答3:


After fooling around for a bit, the most concise way I could get the job done was

subprocess.call(['ls','bob.asc.gz']) == 0

which returns True if the file exists in the directory. This is the behavior I would expect from

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

but for some reason Python won't accept files with extension .gz as files when passed to os.path.isfile.

I don't feel like my solution is very elegant, but it is concise. If someone has a more elegant solution, I'd love to see it. Thanks.



来源:https://stackoverflow.com/questions/23021517/check-if-gzip-file-exists-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!