【问题标题】:Update pandas data into existing csv将 pandas 数据更新为现有的 csv
【发布时间】:2019-12-04 10:59:13
【问题描述】:

我有一个从 pandas 数据框创建的 csv。

但是一旦我附加它,它就会抛出:OSError: [Errno 95] Operation not supported

for single_date in [d for d in (start_date + timedelta(n) for n in range(day_count)) if d <= end_date]:
  currentDate = datetime.strftime(single_date,"%Y-%m-%d")
  #Send request for one day to the API and store it in a daily csv file
  response = requests.get(endpoint+f"?startDate={currentDate}&endDate={currentDate}",headers=headers)
  rawData = pd.read_csv(io.StringIO(response.content.decode('utf-8')))


  outFileName = 'test1.csv'
  outdir = '/dbfs/mnt/project/test2/'
  if not os.path.exists(outdir):
    os.mkdir(outdir)

  fullname = os.path.join(outdir, outFileName)    


  pdf = pd.DataFrame(rawData)
  if not os.path.isfile(fullname):
    pdf.to_csv(fullname, header=True, index=False)
  else: # else it exists so append without writing the header
    with open(fullname, 'a') as f: #This part gives error... If i write 'w' as mode, its overwriting and working fine.
      pdf.to_csv(f, header=False, index=False, mode='a')

【问题讨论】:

  • 不确定这是否有帮助,但有几次我读到 pandas 的文件方法不应该获取句柄,而是文件名/路径。此外,有了这个你就不需要上下文管理器,因为函数本身负责关闭(如果你给它一个路径)。
  • @OlegO 我已经尝试过不使用上下文管理器。但它同样的错误。
  • 这行我没看懂:pdf.to_csv(f, header=True, index=False) what's f in here?
  • @OlegO 对不起,我想我写错了。刚刚更正了第一个 pdf.to_csv

标签: python-3.x pandas azure-databricks


【解决方案1】:

我猜是因为您以附加模式打开文件,然后在调用to_csv 时再次传递mode = 'a'。你能试着简单地这样做吗?

pdf = pd.DataFrame(rawData)
if not os.path.isfile(fullname):
    pdf.to_csv(fullname, header=True, index=False)
else: # else it exists so append without writing the header
    pdf.to_csv(fullname, header=False, index=False, mode='a')

【讨论】:

    【解决方案2】:

    它没有解决,附加。所以我创建了 parque 文件,然后将它们作为数据框读取。

    【讨论】:

      【解决方案3】:

      我遇到了类似的问题,根本原因是 Databrick Runtime > 6 不支持对 DBFS 中存在的文件进行追加或随机写入操作。在我按照他们的建议将运行时从 5.5 更新到 6 之前,它对我来说工作正常,因为当时他们不再支持 Runtime

      我按照这个解决方法,用代码读取文件,附加数据,然后覆盖它。

      【讨论】:

        猜你喜欢
        • 2017-06-11
        • 2014-05-03
        • 1970-01-01
        • 2022-12-07
        • 2022-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多