Error: Cannot open file for writing -- write_csv

Hello,

Over this past weekend, I ran a mass update on packages that were in my queue. Ever since then, I have been having issues with using write_csv to overwrite the .csv file that I had just read in.

I am updating my Statcast baseball database each day using the 'baseballr' package. I load in the old data, download the new data for the previous day of games, combine the two data frames, create a new data frame with a filtered data set, and then overwrite the existing csv's. However, since the updates, I get an error message that says "Error: Cannot open file for writing" when I do the first write_csv command; however, I have no issues with the second command.

library(tidyverse)
library(baseballr)

sc_old = read_csv("SavantHittingData21.csv")

sc21 = baseballr::scrape_statcast_savant(start_date = Sys.Date()-1, end_date = Sys.Date()-1, player_type = 'batter')

sc_b = rbind(sc21, sc_old)

sc21_events = sc_b %>%
  filter(type == "X")

write_csv(sc_b,"SavantHittingData21.csv")  # 1.
write_csv(sc21_events, "SavantHittingData21_EventsOnly.csv") # 2.

I created a copy of the .csv file in my folder and tried deleting the original, but got an error message saying the file was open in my R Studio session. Is there a new issue that does not allow R Studio to close out the .csv file after I originally read it in (sc_old)? I was able to work around the error by messing around in the debugging menu a placing a breakpoint on the line of code, but I have no idea why that allowed it to run.

This is my first post so I hope it translates well. I did not include a reprex because I was not sure how to include a .csv file stored on my computer, but I will if it would help.

Thanks!

Update:

I have no idea why this works, but I wanted to pass this along for anyone with the same issue. I added a line of code 'View(dataframe)' before the first write_csv command and it works fine now. Not a great fix, but it seems to be working, at least temporarily while I figure out a better solution

Hey,

I encountered the same issue and it was very frustrating i couldnt get your solution to work.

I think i may have found a solution.

In your read_csv function try adding lazy = FALSE so it reads sc_old = read_csv("SavantHittingData21.csv", lazy = FALSE). This is what solved the solution for me let me know if it works

1 Like

That appears to work! Thank you very much for pointing that out, I had not come across that solution anywhere and that is definitely a much better one than my temporary fix (which I still don't know why it worked).

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.