to_csv append mode is not appending to next new line

2024/10/13 4:24:02

I have a csv called test.csv that looks like:

accuracy    threshold   trainingLabels
abc         0.506       15000
eew         18.12       15000

And then a dataframe called summaryDF that looks like:

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.

Answer

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.

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. You are not closing the global file f because the variable was overshadowed by the f in that scope.

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.

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. 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.

https://en.xdnf.cn/q/118124.html

Related Q&A

Optional keys in string formats using % operator?

Is is possible to have optional keys in string formats using % operator? I’m using the logging API with Python 2.7, so I cant use Advanced String Formatting.My problem is as follow:>>> impor…

HDF5 headers missing in installation of netCDF4 module for Python

I have attempted to install the netCDF4 module several times now and I keep getting the same error:Traceback (most recent call last):File "<string>", line 17, in <module>File &quo…

How to catch network failures while invoking get() method through Selenium and Python?

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this:If I reload the page 99% it will load fine, what is the proper…

Pandas crosstab with own function

I have a function which takes two inputs and returns a float e.g. my_func(A, B) = 0.5. I have a list of possible inputs: x = [A, B, C, D, E, F].I want to produce a square matrix (in this case 6 by 6) …

Using a custom threshold value with tf.contrib.learn.DNNClassifier?

Im working on a binary classification problem and Im using the tf.contrib.learn.DNNClassifier class within TensorFlow. When invoking this estimator for only 2 classes, it uses a threshold value of 0.5 …

How to remove certain characters from a variable? (Python)

Lets suppose I have a variable called data. This data variable has all this data and I need to remove certain parts of it while keeping most of it. Lets say I needed to remove all the , (commas) in thi…

criticism this python code (crawler with threadpool)

how good this python code ? need criticism) there is a error in this code, some times script do print "ALL WAIT - CAN FINISH!" and freeze (no more actions are happend..) but i cant find reas…

cx_Freeze executable not displaying matplotlib figures

I am using Python 3.5 and I was able to create an executable using cx_Freeze but whenever I try to run the executable it runs without error but it cannot display any matplotlib figure. I have used Tkin…

Saving variables in n Entry widgets Tkinter interface

Firstly apologises for the length of code but I wanted to show it all.I have an interface that looks like this:When I change the third Option Menu to "List" I will add in the option to have n…

Pulling the href from a link when web scraping using Python

I am scraping from this page: https://www.pro-football-reference.com/years/2018/week_1.htmIt is a list of game scores for American Football. I want to open the link to the stats for the first game. The…