Pandas无法在一夜之间打开csv文件



我正在构建一个脚本,生成一个csv文件与熊猫,但我试图使它,所以如果文件已经存在于指定的路径,脚本只会追加到现有的文件,而如果文件不存在,它将创建一个新的信息。

我现在的代码是这样的:

#Trying to find the file in the designated path and then appending the new info
try:
pd.read_csv('file.csv', encoding = 'ANSI')
info.to_csv('file.csv', index = False, header = None, sep = ';', encoding = 'ANSI', decimal = ',', mode = 'a')
#Creating a new file into the existing path if it doesn't exist
except IOError:
info.to_csv('file.csv',  index = False, sep = ';', encoding = 'ANSI', decimal = ',', header = True)

这在白天工作得很好,但是当我试图在第二天运行脚本时,pd.read_csv()遇到以下错误:

ParserError:标记数据错误。C错误:预期第10行有1个字段,看到2

我读到解决这个问题的一种方法是添加参数error_bad_lines = False,但这会导致指数级的计算时间变慢。本例中的详细信息显示,.csv文件的几乎每一行都有一些额外的n

是否有其他方法来解决这个文件附加/创建问题?

我需要能够在excel中打开这个文件来检查里面的信息。我应该尝试创建。xlsx文件而不是。csv文件吗?

使用pathlib检查文件是否已经存在。如果你真的想加载整个文件(只是为了检查它是否存在),你需要使用与pd.to_csv设置相同的参数。但是对于一个简单的检查,后者在计算上是非常昂贵的,所以我建议使用pathlib

pd.read_csv中的默认分隔符是,(这是您的十进制分隔符),因此错误可能是由于试图读取带有错误分隔符的文件(更多信息在这里)。

可能的解决方案:

from pathlib import Path
if Path('file.csv').exists():
info.to_csv('file.csv', index = False, header = None, sep = ';', encoding = 'ANSI', decimal = ',', mode = 'a')
else:
info.to_csv('file.csv',  index = False, sep = ';', encoding = 'ANSI', decimal = ',', header = True)

最新更新