繁体   English   中英

获取目录和子目录中所有.gz文件的大小 - python

[英]Get the size of all .gz files in directory and subdirectories - python

我试图遍历目录中的所有压缩文件并保持其大小。 我看到我可以在不提取它的情况下做到这一点,但是当我尝试这样做时,我得到一个错误:“IOError:[Errno 2]没有这样的文件或目录:'first_gz_file。*。gz'”当我在寻找它,我可以找到它,所以我不明白为什么我会得到错误。

这是我的代码:

for directories in chosen_dirs:
    for root,dir,file in os.walk(directories):
        for o in file: 
            if o.endswith('.gz'):
                print (o)
                input_file = gzip.open(o, 'rb')
                try:
                    print(input_file.size)
                finally:
                    input_file.close()

它会正确打印o文件(如果我删除它下面的行)

那里出了什么问题? 谢谢

不要打开文件使用os.path.getsize(path)

至于出了什么问题,快速检查表明gzip对象没有size方法:

>>> g = gzip.open('temp.gz', 'wb')
>>> dir(g)
['__abstractmethods__', '__class__', '__delattr__', '__doc__', '__enter__', 
'__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__',
'__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_abc_cache', 
'_abc_negative_cache', '_abc_negative_cache_version', '_abc_registry', 
'_add_read_data', '_checkClosed', '_checkReadable', '_checkSeekable', 
'_checkWritable', '_check_closed', '_init_read', '_init_write', '_read', 
'_read_eof', '_read_gzip_header', '_unread', '_write_gzip_header', 'close', 
'closed', 'detach', 'filename', 'fileno', 'flush', 'isatty', 'max_read_chunk', 
'myfileobj', 'next', 'read', 'read1', 'readable', 'readinto', 'readline', 
'readlines', 'rewind', 'seek', 'seekable', 'tell', 'truncate', 'writable', 
'write', 'writelines']
>>> 

我想添加不要使用filedir作为变量名,因为它们都是python中的保留字,你可能需要在原始上下文中使用它们也是你正在使用它们的上下文中的列表所以使用root, dirs, filesroot, dir_list file_list为清楚起见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM