如何解决使用Python3-需要生成压缩的csv文件以用于熊猫的流输出
我是python的新手。 Kinldy帮助我直接为流数据创建压缩的csv文件。
详细信息:每次调用函数时,我的csv文件应更新。我不想创建一个.csv文件,而是想创建一个压缩的.csv文件来流式传输数据。
注意:我的数据不是一口气生成的。 df.to_csv(...,compression =“ gzip”)在我的情况下不起作用。
再次提出这个问题,因为我先前的问题被标记为重复并已结束。
Trail1:
def outputfile(result):
try:
table = pd.DataFrame(result)
table = table.transpose()
headers = ['IP','account','fd','instance_id','index','sourcetype','Product','State']
if os.path.isfile(final_IP_List_Program_Output_csv):
mode = 'a'
header = 0
else :
mode ='w'
header = headers
with open(final_IP_List_Program_Output_csv,mode=mode,newline='',encoding='utf8',errors='replace') as csvfile:
content = table.to_csv(csvfile,sep=',',encoding='utf-8',index=False,line_terminator="",header=header,quoting=csv.QUOTE_NONE)
print("Successfully uploaded the csv file.")
with gzip.open(final_IP_List_Program_Output_csv_gz,'a') as compressed_file:
compressed_file.write(table.to_csv(content,quoting=csv.QUOTE_NONE).encode())
print("Successfully uploaded the compressed file")
except Exception as err :
print("Error Occurred during FileCreation. Kindly recheck the code.",err)
sys.exit()
此函数被调用以更新每一行。使用上述方法,我首先创建一个csv文件,然后创建一个压缩的csv文件。但是我压缩后的csv文件本身的大小比普通csv文件大。
足迹2:
tf = tarfile.open(final_IP_List_Program_Output_csv_gz,mode="w:gz")
table = pd.DataFrame(result)
with open(final_IP_List_Program_Output_csv,errors='replace') as file:
table.to_csv(file,quoting=csv.QUOTE_NONE)
tf.add(final_IP_List_Program_Output_csv,arcname=os.path.basename(final_IP_List_Program_Output_csv))
tf.close()
print("Successfully uploaded the csv file.")
使用此命令,我只能将第一行添加到tar.gz文件中,但是原始的csv文件包含多行。
解决方法
with open(final_IP_List_Program_Output_csv,mode=mode,newline='',encoding='utf8',errors='replace') as csvfile:
table.to_csv(csvfile,sep=',',encoding='utf-8',index=False,line_terminator="",header=header,quoting=csv.QUOTE_NONE)
print("Successfully uploaded the csv file.")
tf.add(final_IP_List_Program_Output_csv,arcname=os.path.basename(final_IP_List_Program_Output_csv))
tf.close()
print("Successfully uploaded the compressed file")
以上方法有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。