2017-06-22 76 views
0

我想有這樣的電話:讀取壓縮標準輸入

pv -ptebar compressed.csv.gz | python my_script.py 

裏面my_script.py我想解壓compressed.csv.gz和使用Python CSV解析器解析它。我希望這樣的事情:

import csv 
import gzip 
import sys 


with gzip.open(fileobj=sys.stdin, mode='rt') as f: 
    reader = csv.reader(f) 
    print(next(reader)) 
    print(next(reader)) 
    print(next(reader)) 

當然它不會因爲gzip.open工作沒有fileobj說法。你能提供一些解決這個問題的實例嗎?

UPDATE

Traceback (most recent call last): 
    File "my_script.py", line 8, in <module> 
    print(next(reader)) 
    File "/usr/lib/python3.5/gzip.py", line 287, in read1 
    return self._buffer.read1(size) 
    File "/usr/lib/python3.5/_compression.py", line 68, in readinto 
    data = self.read(len(byte_view)) 
    File "/usr/lib/python3.5/gzip.py", line 461, in read 
    if not self._read_gzip_header(): 
    File "/usr/lib/python3.5/gzip.py", line 404, in _read_gzip_header 
    magic = self._fp.read(2) 
    File "/usr/lib/python3.5/gzip.py", line 91, in read 
    self.file.read(size-self._length+read) 
    File "/usr/lib/python3.5/codecs.py", line 321, in decode 
    (result, consumed) = self._buffer_decode(data, self.errors, final) 
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte 

回溯上述申請@Rawing建議後出現。

+0

您是否試圖轉儲一些'f.readline()'結果來查看您的解壓縮流是什麼樣的? – 9000

回答

0

使用gzip.open(sys.stdin.buffer, 'rt')修復問題爲Python 3

2

在蟒蛇3.3+,你可以把一個文件對象gzip.open

The filename argument can be an actual filename (a str or bytes object), or an existing file object to read from or write to.

所以,你的代碼應該工作,如果你只是省略fileobj=

with gzip.open(sys.stdin, mode='rt') as f: 

或者,會更有效解決方案:

with gzip.open(sys.stdin.buffer, mode='rb') as f: 

如果由於某種奇怪的原因,您使用的是比3.3更早的python,則可以直接調用gzip.GzipFile constructor。然而,gzip模塊的這些老版本沒有以文本方式打開文件的支持,所以我們將使用sys.stdin的,而不是潛在的緩衝區:

with gzip.GzipFile(fileobj=sys.stdin.buffer) as f: 
+0

'TypeError:強制爲Unicode:需要字符串或緩衝區,找到文件'。當stdin已經打開時,它並不讓我感到驚訝。 – pt12lol

+0

好的,我嘗試了Python 3的'gzip.open',它實際上改變了一個錯誤。目前我有一個涉及編碼的問題:'UnicodeDecodeError:'utf-8'編解碼器無法解碼位置1中的字節0x8b:無效的起始字節。你還能幫忙嗎? – pt12lol

+0

該問題已更新。 – pt12lol