What I want to do is to open csv file, make changes inside and save it. My code looks like this:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath, FileFormat=FileFormat.xlCSV)
This code kinda works but when it saves the file it asks me if i want to overwrite the file since it already exists.
So what I did was to save it as "csv.txt" file, then remove the ".csv" file and rename ".csv.txt" file back to ".csv" file using code below:
savePath = r'D:\file.csv'
with xw.App(visible=True) as app:
wb = app.books.open(savePath)
sheet1 = wb.sheets[0]
saveDF = sheet1.range(wb.sheets[0].used_range.address).options(pd.DataFrame, chunksize=30_000, index=False).value
wb.sheets[0].clear()
wb.sheets[0].range('A1').options(index=False, header=True).value = saveDF
wb.api.SaveAs(savePath + '.txt', FileFormat=FileFormat.xlCSV)
os.remove(savePath)
os.rename(savePath + '.txt', savePath)
Issue I have here is that I get error:
"PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:"
Which means that Python tries to rename files while its being saved.
So my questions are:
Is there a way to overwrite csv file without needing to manually click "file already exists - do You want ot ovewrite it" prompt ?
Is there anything I can change in my code to not get [WinError 32] shown above ?
How can I change my code to not open two instances of excel (now it opens blank one - probably when I use "with" statement and second one with my file when I use app.books.open) ?
Thank You in advance for any kind of help.