[英]In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories
[英]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']
>>>
我想添加不要使用file
和dir
作為變量名,因為它們都是python中的保留字,你可能需要在原始上下文中使用它們也是你正在使用它們的上下文中的列表所以使用root, dirs, files
或root, dir_list file_list
為清楚起見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.