r - 使用循环在R中移动多个文件
问题描述
我知道有一些问题与我的非常相似,但我有不同而奇怪的问题。
我正在编写一个脚本,它将文件从一个位置存档到另一个位置。问题是,当我在循环中对多个文件使用 file.rename() 时,或者如果我尝试在 1 行中使用旧路径向量和新路径向量时,R 不会移动文件。例如
for (i in 1:length(old_files_all)) {
try(file.rename(from = file.path(old_files_all[i]), to = file.path(new_paths[i])))
#or without try/file.path inside of method ^
}
这样的循环不会移动文件,但是当我为循环的每个位置手动运行代码时,例如:
try(file.rename(from = file.path(old_files_all[1]), to = file.path(new_paths[1])))
有用....
你们能帮我吗,如何解决这个“问题”。提前致谢。
解决方案
您可以直接将 file.rename 与向量一起使用,无需循环。
#create some example files
file.create(paste0("test", formatC(1:10, width = 2, flag = "0"), ".txt"))
#create vectors with old and new file names
files_old <- list.files(pattern = "^test[0-9]{2}\\.txt", getwd())
files_new <- paste0(getwd(), "//Delete//", files_old)
#move files
file.rename(from = files_old, to = files_new)
推荐阅读
- python - 在初学者级别理解 Python for 循环
- vba - 检索(修改)压缩文件中列出的所有文件的日期
- json - 在 Angular 9 中解析 JSON 对象并使用 {{ item | 返回 HTML 模板中的输出 json}}
- c++ - 链接阶段在 Ubuntu 但不是 MacOS 上失败
- python-3.x - 将在线新闻文章网站的每个子链接的 Scrapy 写入单独的多个文件
- javascript - Lightning Web 组件中的可跟踪数组排序
- python - 迭代我的列表不会返回我想要的值
- ios - Xcode 只显示启动故事板,不显示其余部分
- ssrs-2012 - 如何在 ssrs 中查看用户数据?
- python - 使用python增加图像中特定像素的亮度