0

Is it possible to overwrite and save a DataFrame to an Excel or CSV file if that file is already open?

I tried using df.to_excel("file.xlsx", index=False) to overwrite an existing Excel file that I had open. I expected pandas to save the df and replace the file contents, but instead it raised a permission error because the file was already open in Excel.

1
  • is this good idea? Let say you write it with Pandas but later Excel writes it and removes all what you wrote with Pandas. Commented Sep 25 at 1:28

1 Answer 1

0

If you're working on Windows, you cannot open a file for writing that's already open for reading, Windows has strict locks against that (unlike Linux).

So, if you want to use df.to_excel(), you'll have to first find your open file handle, and close it before you get here in the code.

I've encountered this issue a number of times, my solution is usually to open files in a with block so that they get closed immediately after reading.

Sign up to request clarification or add additional context in comments.

2 Comments

While this is correct in some sense, it is not universally true. As a counter example, one can open a csv in libreoffice the happily edit or replace the contents it with some other tool or app or even delete the file. It happens to be the case that some tools like ms office want to lock files while open.
Interesting. But it's not just MS Office. On Windows, f = open("foo") will prevent you from deleting foo until you call f.close(). Although to my surprise, I was just able to do open("foo", "w"), I did not expect that. So you're right, it's not all exclusive!

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.