循环遍历压缩的 gzip 文件会在第二次迭代时抛出"ERROR [Errno 2] No such file or directory: 'part-r-00001.gz'" - Python



我正在循环s3桶中的多个文件。第一次迭代工作得很好,但是一旦跳转到下一个,我收到一个"ERROR [Errno 2] No such file or directory: 'part-r-00001.gz'"。(part-r-00000.gz被正确访问)

我不知道为什么没有找到文件,因为它在桶中可用。

这是代码:

BUCKET = 'bucket'
PREFIX = 'path'
now = datetime.utcnow()
today = (now - timedelta(days=2)).strftime('%Y-%m-%d')
folder_of_the_day = PREFIX + today + '/'
logger.info("map folder: %s", folder_of_the_day)
client = boto3.client('s3')
response = client.list_objects_v2(Bucket=BUCKET, Prefix=folder_of_the_day)
for content in response.get('Contents', []):
bucket_file = os.path.split(content["Key"])[-1]
if bucket_file.endswith('.gz'):
logger.info("----- starting with file: %s -----", bucket_file)
try:
with gzip.open(bucket_file, mode="rt") as file:
for line in file:
//do something
except Exception as e:
logger.error(e)
logger.critical("Failed to open file!")
sys.exit(4)

第二轮执行后,输出如下:

2022-06-18 12:14:48,027 [root] INFO -----以file开头:part-r-00001.gz ----- 2022-06-18 12:14:48,028 [root] ERROR [Errno 2]没有这样的文件或目录:'part-r-00001.gz'

Update根据注释,我将代码更新为正确的gzip方法,但错误仍然存在。一旦第一次迭代完成,第二个文件就找不到了。

更新后的代码:

try:
with gzip.GzipFile(bucket_file) as gzipfile:
decompressed_content = gzipfile.read()
for line in decompressed_content.splitlines():
//do something
break

我认为你不能直接在S3路径上使用gzip.open

您可能需要一个合适的gzip方法来读取S3 bucket中的文件。

用Python从AWS S3读取gzip文件的内容

相关内容

最新更新