简体   繁体   English

to_csv追加模式未追加到下一个新行

[英]to_csv append mode is not appending to next new line

I have a csv called test.csv that looks like: 我有一个名为test.csv的csv,如下所示:

accuracy    threshold   trainingLabels
abc         0.506       15000
eew         18.12       15000

And then a dataframe called summaryDF that looks like: 然后是一个名为summaryDF的数据summaryDF ,如下所示:

accuracy    threshold   trainingLabels
def         0.116       342
dja         0.121       1271

I am doing: 我在做:

try:
        if os.stat('test.csv').st_size > 0:
                summaryDF.to_csv(path_or_buf=f, encoding='utf-8', mode='a', header=False)
                f.close()
        else:
            print "empty file"
            with open('test.csv', 'w+') as f:
                summaryDF.to_csv(path_or_buf=f, encoding='utf-8')
                f.close()
    except OSError:
        print "No file"
        with open('test.csv', 'w+') as f:
            summaryDF.to_csv(path_or_buf=f, encoding='utf-8')
            f.close()

Because I want my file to be: 因为我希望我的文件是:

accuracy    threshold   trainingLabels
abc         0.506       15000
eew         18.12       15000
def         0.116       342
dja         0.121       1271

Instead, it is: 相反,它是:

accuracy    threshold   trainingLabels
abc         0.506       15000
eew         18.12       15000def            0.116       342   
dja         0.121       1271

How can I solve this? 我该如何解决? I am guessing using a CSV writer instead of to_csv but clearly the append mode is not skipping the last line of the existing file. 我猜测使用的是CSV to_csv而不是to_csv但显然附加模式不会跳过现有文件的最后一行。

Are you using the pandas package? 您在使用熊猫包吗? You do not mention that anywhere. 您在任何地方都不会提及。

Pandas does not automatically append a new line, and I am not sure how to force it. 熊猫不会自动添加新行,我不确定如何强制使用新行。 But you can just do: 但是您可以这样做:

f.write('\n')
summaryDF.to_csv(path_or_buf=f, mode='a', ...)

An unrelated bug in your code: 您的代码中不相关的错误:

You seem to have a global file object called f . 您似乎有一个名为f的全局文件对象。

When you do this: 执行此操作时:

with open('test.csv', 'w+') as f:
    ...
    f.close()

The file that you are closing there is the file that you just opened in the with block. 您要关闭的文件是您在with块中刚刚打开的文件。 You are not closing the global file f because the variable was overshadowed by the f in that scope. 您没有关闭全局文件f因为变量在该作用域中被f所覆盖。

Is this what you want? 这是你想要的吗? Either way, it makes no sense. 无论哪种方式,都没有意义。 The reason why we use the with scope is to avoid having to close the file explicitly. 我们使用with范围的原因是避免必须显式关闭文件。

You either use: 您可以使用:

f = open('filename')
...
f.close()

OR 要么

with open('filename') as f:
    ...

You do not close a file opened within a with block. 您不会关闭在with块中打开的文件。 Using a with block has the additional advantage that the file gets closed even if an exception is raised and the following code is not executed. 使用with块还具有另一个优点,即使引发异常并且不执行以下代码,文件也会被关闭。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM