簡體   English   中英

無法使用 AWS Lambda 從 AWS S3 讀取 .gz 文件

[英]cant read .gz file from AWS S3 using AWS Lambda

我正在嘗試使用 AWS Lambda 從 S3 讀取 .gz 文件。

當我嘗試使用 gzip 解壓縮文件時,出現OSError: Not a gzipped file (b'PK')錯誤。

這是代碼...

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)

這是 retr 文件的響應。

{  
   '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>
}

如何解壓縮該 .gz 文件? 我想解壓縮它並讀取該 .gz 文件中的 .txt 文件。 任何人都可以指導我嗎?

您嘗試解壓縮的文件不是 gzip 文件。 這是一個 ZIP 文件。

以下是我嘗試使用 Python gzip 模塊解壓縮 ZIP 文件的原因:

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')

您將需要改用zipfile 模塊

我正在上傳損壞的 .gz 文件。 代碼很好,現在運行良好。

首先確保它是 .gz 或 .zip,如果是 .zip,則使用zipfile而不是gzip

import zipfile
Fileobj=zipfile.ZipFile(....)

這在AWS Lambda上對我AWS Lambda

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM