Python Pandas无法覆盖csv文件"OSError:[Errno 22]无效参数". [英] Python Pandas unable to overwrite a csv file "OSError: [Errno 22] Invalid argument"

查看:94
本文介绍了Python Pandas无法覆盖csv文件"OSError:[Errno 22]无效参数".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了许多有关Errno 22的答案,但没有特定于熊猫的内容,也没有关于仅在覆盖时不写入的情况(初始写入成功).

I have found many answers relating to Errno 22 but nothing pandas specific and nothing where it is only on overwrite not on write (initial write succeeds).

因此,我成功使用以下python脚本重新创建了该错误:

So ive managed to recreate the bug with the following python script:

import pandas as pd

print('path:')
path = input()

data = pd.DataFrame(data=[1,2,3], columns=['index'])
data.to_csv(path, encoding='utf-8', index=False)

data = data.append(pd.DataFrame(data=[4,5,6], columns=['index']))
data.to_csv(path, encoding='utf-8', index=False)

因此对to_csv的第一次调用将写入以下文件

so the first call to to_csv writes the following file

index
1
2
3

但是第二次调用to_csv会导致错误:

but the second call to to_csv causes the error:

OSError: [Errno 22] Invalid argument: '[path omitted]/python/bug'

非常感谢您的帮助:)

推荐答案

我发现的解决方案是使用os.remove(path):

The solution i have found is to use os.remove(path):

import pandas as pd
import os

print('path:')
path = input()

data = pd.DataFrame(data=[1,2,3], columns=['index'])
data.to_csv(path, encoding='utf-8', index=False)

if(os.path.exists(path)):
    os.remove(path)

data = data.append(pd.DataFrame(data=[4,5,6], columns=['index']))
data.to_csv(path, encoding='utf-8', index=False)

可惜to_csv没有覆盖模式

its a shame to_csv doesnt have an overwrite mode

这篇关于Python Pandas无法覆盖csv文件"OSError:[Errno 22]无效参数".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆