我使用下面的Python3外壳代码从S3存储桶中读取数据,提取数据并写入同一个桶中的新文件。但是写操作不起作用,Medicaid_Provider_ID_.txt被填充为零行。有线索吗?
import logging
import boto3
s3 = boto3.client("s3")
data = s3.get_object(Bucket='mmis.request.file', Key='MEIPASS_FISCAL_TRANS_ONE_RECORD.TXT')
file_lines = data['Body'].iter_lines()
next(file_lines)
new = []
id = 1
for line in file_lines:
line_split = line.decode().split(',')
MEDICAID_PROVIDER_ID = line_split[0]
REASON_CODE = line_split[1]
with open("Medicaid_Provider_ID_.txt","w") as f:
f.writelines(MEDICAID_PROVIDER_ID)
f.close()
id += 1
new = s3.put_object(Bucket='mmis.request.file', Key='Medicaid_Provider_ID_.txt')发布于 2022-03-18 17:05:08
这一行代码每次运行代码时都会重新创建您的文件:
with open("Medicaid_Provider_ID_.txt","w") as f:您应该打开/创建文件一次,然后遍历文件中的所有行,然后在完成时关闭该文件。就像这样:
import logging
import boto3
s3 = boto3.client("s3")
data = s3.get_object(Bucket='mmis.request.file', Key='MEIPASS_FISCAL_TRANS_ONE_RECORD.TXT')
file_lines = data['Body'].iter_lines()
next(file_lines)
new = []
id = 1
# Open the file
with open("Medicaid_Provider_ID_.txt","w") as f:
# Write each line of the file
for line in file_lines:
line_split = line.decode().split(',')
MEDICAID_PROVIDER_ID = line_split[0]
REASON_CODE = line_split[1]
f.writelines(MEDICAID_PROVIDER_ID)
# Close the file
f.close()
id += 1
new = s3.put_object(Bucket='mmis.request.file', Key='Medicaid_Provider_ID_.txt')https://stackoverflow.com/questions/71530637
复制相似问题