Home > OS >  Unzip a zipped file that is saved using name and date of download like this (Query Transaction Histo
Unzip a zipped file that is saved using name and date of download like this (Query Transaction Histo

Time:11-27

I have a data related problem,

I want to unzip a file in my download folder.

This zip file is for daily use, meaning that is something I will keep downloading on a daily basis and the zip folder name usually contain date and time of download as the folder name. This is how the zip folder name usually looks like below.

Query Transaction History_20221125035935_42217.zip

and the excel file in the folder comes like this

Query Transaction History_20221126035617_01.xls

If you check closely the name for the both the zip file and xls are combination of name(Query Transaction History_) and date and time of the download (20221126035617_01)

So I was able to come up with the script below.

library(plyr)

my_dir<-"C:/Users/Guest 1/Downloads"

zip_files <-list.files(path ="C:/Users/Guest 1/Downloads",
    pattern ="Query Transaction History_20221126.*zip",full.names = TRUE )

 ldply(.data =zip_files,.fun = unzip,exdir =my_dir )

it works fine and extract the file to the download folder. But it is something that i will be keep doing on a daily basis and the date will keep changing while the name is constatcnt so i tried this code.

library(glue)

sea<-format(Sys.Date(),"%Y%m%d") #formatting date to suit the date attached to zip file

zip_files <-list.files(path ="C:/Users/Guest 1/Downloads",
    pattern =glue("Query Transaction History_{sea}.*zip",full.names = TRUE )) #using glue to glue the date variable and attached it to the zipped file and run.

It works fine

Now to unzip using apply function below

 ldply(.data =zip_files,.fun = unzip,exdir =my_dir )#using apply to unzip

I get the error below

Warning message:
In FUN(X[[i]], ...) : error 1 in extracting from zip file

Thanks

CodePudding user response:

With the zip files residing outside your getwd() you'll need to specify the full file path like so:

ldply(.data =zip_files,
      .fun = function(file_name){ 
                unzip(file.path("C:/Users/Guest 1/Downloads", 
                                file_name),
                exdir = my_dir
                )
              }
)

Note: unless you require {plyr} anyway, you could just use base R sapply or Map instead of ldply.

  • Related