【问题标题】:How can I ensure a dataframe has completed being written via pandas.to_csv()?如何确保数据帧已通过 pandas.to_csv() 完成写入?
【发布时间】:2021-05-30 16:25:14
【问题描述】:

我一直在创建一个查询数据库并返回结果的小脚本。然后,我一直在使用 Pandas.to_csv() 将其写入 CSV 临时文件,然后再将该 CSV 结果上传到云位置。我遇到的麻烦是确保 pandas.to_csv() 函数在将 CSV 临时文件上传到云位置之前已完成写入。我一直确保该日期在上传之前进入临时文件的唯一方法是保留

打印(temp.tell())

下面示例中的代码行。如果我将其注释掉,则不会上传任何数据。

示例代码如下:

def write_to_temporary_csv_file(df, file_name, token, folder_id):
   with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as temp:
       print("DataFrame: ", df)
       df.to_csv(temp, index=False, encoding='utf-8')
       print("temp.tell() size: ", temp.tell())
       print("File size: ", str(round((os.stat(temp.name).st_size/1024), 2)), "kb")
       new_file_path = tempfile.gettempdir() + '/' + customer_name + '_' + file_name + '_' +  current_date + '.csv'

       ## Check if newly created renamed temp file already exist, if it does remove it to create it
       remove_temporary_file(new_file_path)
       os.link(temp.name, new_file_path)
       upload_response = upload_file(token, folder_id, new_file_path)

       ## Remove both the temp file and the newly created renamed temp file
       remove_temporary_file(temp.name)
       remove_temporary_file(new_file_path)

图 1(包括 temp.tell(): 图 2(带有 temp.tell() 注释掉:

【问题讨论】:

  • 那为什么写不完呢? to_csv 不会完成并且不会引发错误的情况并不多,对吧?也许是一个完整的磁盘?您还担心 pandas 中的代码会在没有真正完成文件写入的情况下返回?
  • 你的 with 语句是否在 porpuse 上被注释掉了?
  • 主要问题是 df.to_csv() 已返回 0 数据,如前所述,如果我删除该 print(temp.tell()) 我几乎总是得到 os.stat(temp.name ).st_size 返回 0 的大小。另外,刚刚检查了我的磁盘有足够的空间,所以这不是问题。这是一个自动化的过程,我希望返回带有数据的文件的可靠性尽可能接近 100%。将在一秒钟内使用输出更新示例代码
  • @Raphael,不,不是,胖手指。

标签: python pandas temporary-files


【解决方案1】:

我认为这可能是由于您保持文件打开(只要您在 with 块内)。这可能会导致内容未刷新到磁盘。

def write_to_temporary_csv_file(df, file_name, token, folder_id):
   with tempfile.NamedTemporaryFile(mode='w', suffix='.csv', delete=False) as temp:
       print("DataFrame: ", df)
       df.to_csv(temp, index=False, encoding='utf-8')

   # at this point we can close the file by exiting the with block

   print("temp.tell() size: ", temp.tell())
   print("File size: ", str(round((os.stat(temp.name).st_size/1024), 2)), "kb")
   new_file_path = tempfile.gettempdir() + '/' + customer_name + '_' + file_name + '_' +  current_date + '.csv'

   ## Check if newly created renamed temp file already exist, if it does remove it to create it
   remove_temporary_file(new_file_path)
   os.link(temp.name, new_file_path)
   upload_response = upload_file(token, folder_id, new_file_path)

   ## Remove both the temp file and the newly created renamed temp file
   remove_temporary_file(temp.name)
   remove_temporary_file(new_file_path)

【讨论】:

  • 好吧,我会被诅咒的。谢谢!
猜你喜欢
  • 2023-04-03
  • 2020-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
相关资源
最近更新 更多