Reputation: 1651
i'm trying to read a .gz file from S3 using AWS Lambda.
when i try to unzip the file using gzip, i get OSError: Not a gzipped file (b'PK') error.
Here is the code...
retr = s3_client.get_object(Bucket=bucket, Key=key)
print(retr)
bytestream = BytesIO(retr['Body'].read())
print(bytestream)
got_text = GzipFile(mode='rb', fileobj=bytestream).read().decode('utf-8')
print(got_text)
Here is the response of the retr file.
{
'ResponseMetadata':{
'RequestId':'aklsfjdlskfj',
'HostId':'kajsdfhdkjfh/+r+i0OLx/adlksfjd/aksfh=',
'HTTPStatusCode':200,
'HTTPHeaders':{
'x-amz-id-2':'alsdkfjslkfjsalfjflkj/+r+i0OLx/asklfjslk/r9eTM=',
'x-amz-request-id':'hgfhgf',
'date':'Sun, 21 Jan 2018 08:35:28 GMT',
'last-modified':'Sun, 21 Jan 2018 08:32:34 GMT',
'etag':'"aksjdfhdskjfhfkjhf"',
'accept-ranges':'bytes',
'content-type':'application/x-gzip',
'content-length':'2825',
'server':'AmazonS3'
},
'RetryAttempts':0
},
'AcceptRanges':'bytes',
'LastModified':datetime.datetime(2018,
1,
21,
8,
32,
34,
tzinfo=tzutc()),
'ContentLength':2825,
'ETag':'"akjsfhksdjfhsdkfj"',
'ContentType':'application/x-gzip',
'Metadata':{
},
'Body':<botocore.response.StreamingBody object at adsfdsf08>
}
How to get that .gz file unzipped? i want to unzip it and read the .txt file in that .gz file. Can anyone guide me?
Upvotes: 0
Views: 4711
Reputation: 7416
First make sure its .gz or .zip, if .zip, instead of gzip
use zipfile
.
import zipfile
Fileobj=zipfile.ZipFile(....)
This worked for me on AWS Lambda
Upvotes: 0
Reputation: 1651
i was uploading a corrupted .gz file. The code is fine and is working well now.
Upvotes: 0
Reputation: 65024
The file you are trying to decompress is not a gzip file. It's a ZIP file.
Here's what happens why I try to use the Python gzip module to decompress a ZIP file:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import gzip
>>> with gzip.open("ResultList_example2.zip", "rb") as f: data = f.read()
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python36\lib\gzip.py", line 276, in read
return self._buffer.read(size)
File "C:\Python36\lib\gzip.py", line 463, in read
if not self._read_gzip_header():
File "C:\Python36\lib\gzip.py", line 411, in _read_gzip_header
raise OSError('Not a gzipped file (%r)' % magic)
OSError: Not a gzipped file (b'PK')
You will need to use the zipfile module instead.
Upvotes: 1