0

I have created the following function to read a csv file from a given URL:

function(){ 
                        s <- 1;

                        #first get the bhav copy
                        today <- c();ty <- c();tm <- c();tmu <- c();td <- c();

                       # get the URL first
                        today <- Sys.Date()
                        ty <- format(today, format = "%Y")
                        tm <- format(today, format = "%b")
                        tmu <- toupper(tm)
                        td <- format(today, format = "%d")

       dynamic.URL <- paste("https://www.nseindia.com/content/historical/EQUITIES/",ty,"/",tmu,"/cm",td,tmu,ty,"bhav.csv.zip", sep = "")
       file.string <- paste("C:/Users/user/AppData/Local/Temp/cm",td,tmu,ty,"bhav.csv")

                        download.file(dynamic.URL, "C:/Users/user/Desktop/bhav.csv.zip")
                        bhav.copy <- read.csv(file.string)
                        return(bhav.copy)
}

If I run the function, immediately it says that "file.string not found". But when I run it after some time(a few seconds), it executes normally. I think when download.file ecexecutes, it transfers control to read.csv,and it tries to load the file which is not yet properly saved. when i run it after some time, it tries to overwrite the existing file, which it cannot, and the read.csvproperly loads the saved file.`

I want the function to execute the first time I run it. Is there any way or a function to defer the action of read.csvuntil the file is properly saved? Something like this:

download.file(dynamic.URL, "C:/Users/user/Desktop/bhav.csv.zip")
                            wait......
                            bhav.copy <- read.csv(file.string)

Ignore the fact that the destfile in download.file is different from file.string; it is due to function of my system (windows 7).

Very many thanks for your time and effort...

  • Maybe `Sys.sleep` can help here. – kath May 13 '18 at 08:04
  • 1
    It is difficult to duplicate your code, because it depends on your own directory structure, and a url (https://www.nseindia.com/content/historical/EQUITIES/2018/MAY/cm13MAY2018bhav.csv.zip) that does not seem to exist. Can you edit to make a reproducible example? – J. Win. May 13 '18 at 08:20
  • Your presumption is completely wrong. The `read.csv` does not start until the previous line, the `dowload.file`, has finished. This is not Javascript, there is no asynchronous downloading happening. So I have no idea what's going wrong, but I find that you've not assigned your function definition to an object a bit suspicious. It should be something like `getdata = function(){....` and then you call it with `getdata()`. – Spacedman May 14 '18 at 07:47

0 Answers0