2013-12-08 113 views
0

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

这是我的代码:

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文件(如果我删除其下的线)

错在那里? 谢谢

+0

查看glob库http://docs.python.org/3/library/glob.html – uselpa

+0

'glob.glob'只会查找指定的目录,而不会查找其子目录。 –

回答

2

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

至于什么不顺心的快速检查表明,gzip的对象不具有大小的方法:

>>> 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, files或01为清楚起见,请参阅。

相关问题