【发布时间】:2017-01-19 06:39:19
【问题描述】:
我有一个要解压的 zip 文件,然后我使用 for 循环遍历工作目录中的目录,然后将工作目录更改为我刚刚解压的新文件夹。但是,它似乎并不喜欢它。
以下是我使用过的两个代码,其中一个以错误告终,而第二个没有按照我的意愿执行。我想我可能正在混合一些 Python 逻辑?
for (i in list.files("./")){
if (endsWith(tolower(i),"zip")){
unzip(i)
cat("Unzipped",i,"\n")
}
}
for (i in list.dirs(getwd())){
cat("This is i",i,"\n")
Root <- setwd(i)
cat("This is ROOT",Root,"\n")
}
print(Root)
我运行上述代码得到的结果如下:
This is i F:/Testing with R
This is ROOT F:/Testing with R
This is i F:/Testing with R/ABC_Data
This is ROOT F:/Testing with R
如您所见,我希望它遍历文件夹并将 ABC_Data 设为工作目录,以便我可以遍历文件,但它不喜欢它。
我在浏览 Stackoverflow 上的一些页面后尝试的第二个代码是使用 paste0() 修改到下面的,它一直工作到某个点但随后出现错误:
> for (i in list.files("./")){
+ if (endsWith(tolower(i),"zip")){
+ unzip(i)
+ cat("Unzipped",i,"\n")
+ }
+ }
Unzipped GVA_BillData.zip
>
> for (i in list.dirs(getwd())){
+ cat("This is i",i,"\n")
+ Root <- paste0(path.expand(i),"/")
+ cat("This is ROOT",Root,"\n")
+
+ }
This is i F:/Testing with R
This is ROOT F:/Testing with R/
This is i F:/Testing with R/ABC_Data
This is ROOT F:/Testing with R/ABC_Data/
>
> print(Root)
[1] "F:/Testing with R/ABC_Data/"
>
> File_count <- 0
> for (a in list.files(Root)){
+ print(a)
+ if (endsWith(tolower(a),"csv")){
+ if (length(grep("service file",tolower(a)) > 0)){
+ Import <- read.csv(a, header = TRUE)
+ for (i in 1:nrow(Import)){
+ Import_Date <- Import[1,4]
+ if (File_count == 0){
+ write.table(c(Import[i,],Import_Date,a),"Output.csv",append = TRUE,sep = ",",row.names = FALSE,col.names = TRUE)
+ File_count <- File_count + 1
+ } else (write.table(c(Import[i,],Import_Date,a),"Output.csv",append = TRUE,sep = ",",row.names = FALSE,col.names = FALSE))
+ }
+ }
+ }
+ }
[1] "1234_126311.csv"
[1] "Service File.csv"
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'Service File.csv': No such file or directory
> print("Finished")
[1] "Finished"
因此,正如您在第二个代码中看到的那样,它会跳转到文件夹但会抛出错误消息。我也尝试过简单地使用path.expand(i),但这没有用。
【问题讨论】:
标签: r directory subdirectory