0

I am collecting data by using API, and use pandas.to_csv() function by setting as following:

path, mode='a',header=False, index=False'

However, the result is quite weird. The first row collected by API is inserted to other columns instead of the columns I have created.

How to solve this problem? enter image description here

2
  • Are you using multiprocessing/threading or something that which makes your script fast? cuz these types of issues will happen in that type of cases. It's just happening while printing data or that output is from some variable? Commented Aug 1, 2021 at 3:25
  • One of the writes did not write a terminal newline. However, it's hard to say given that you've not shown all that much of your program. Commented Aug 1, 2021 at 3:52

1 Answer 1

1

The file in which you wrote your output did not have a newline character (\n) at the end of the last line. Thus, the following data is added at the end of this line.

Here is an example:

with open('/tmp/file.csv', 'w') as f:
    f.write('1,2')
pd.DataFrame([[3,4],[5,6]]).to_csv('/tmp/file.csv', mode='a', header=0, index=False)

output:

1,23,4
5,6

You either need to ensure that the first write appends a newline at the end of the last line, or you can fix your file using:

with open('/tmp/file.csv', 'a') as f:
    f.write('\n')

right before you to_csv export.

output:

1,2
3,4
5,6

Here is a smarter way to fix your file, it will check if the last character of the file is \n and if not will append one:

with open('/tmp/file.csv', 'r+') as f: # open file as read/append
    f.seek(0, 2)          # go to end of file
    f.seek(f.tell()-1, 0) # come back one chacacter
    if f.read() != '\n':  # if last character is not \n
        f.write('\n')     # then append \n
Sign up to request clarification or add additional context in comments.

1 Comment

Thx! Your answer helps me understand the mechanism of this program!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.