我发现@Kim 的回答最终对我有用,但不是第一次。我想我只是添加一些额外的链接/步骤来帮助我最终到达那里。
关闭并重新打开 R 以便识别环境路径
如果您在执行步骤 1-3 时已经打开了 R,则需要关闭并重新加载 R,以便 R 识别 7z 的环境路径。 @wush978 对这个问题的回答 r system doesn't work when trying 7zip 提供了丰富的信息。我使用 Sys.getenv("PATH") 检查环境路径中是否包含 7zip。
第 4 步。我打开 R 并使用适当的密码输入 system("7z x secure.7z -pPASSWORD")。
我实际上发现这不起作用,所以我按照这篇文章中的说明稍微修改了它,该文章还解释了如何指定输出目录https://*.com/a/16098709/13678913。
如果您已经提取了文件,系统命令会提示您选择是否要使用存档中的文件替换现有文件并提供选项
(Y)es / (N)o / (A)lways / (S)kip all / A(u)to rename all / (Q)uit?
所以修改后的第4步(Y允许替换文件)
system("7z e -ooutput_dir secure.zip -pPASSWORD" Y)
将其完全作为一组修改后的说明
- 安装 7z。
- 使用菜单选项将“C:\Program Files\7-Zip\”添加到我的环境路径(此处为说明https://www.opentechguides.com/how-to/article/windows-10/113/windows-10-set-path.html)
- 关闭并重新打开 R 工作室。输入
Sys.getenv("PATH") 以检查环境中识别的 7zip 的路径(根据 @wush978 对问题 r system doesn't work when trying 7zip 的回答)
- 在控制台中输入
system("7z e -oC:/My Documents/output_dir secure.zip -pPASSWORD") 并使用适当的密码(按照此处的说明https://*.com/a/16098709/13678913)
这里是@Kim的整洁功能的修改版本(包括指定的输出目录和检查现有文件):
我的主脚本
output_dir <- "C:/My Documents/output_dir " #space after directory name is important
zippedfiles_dir <- "C:/My Documents/zippedfiles_dir/"
file_list <- paste0(output_dir , zippedfiles_dir , list.files(path = zippedfiles_dir, pattern = ".zip", all.files = T))
source("unzip7z.R")
源文件 unzip7z.R 中的代码
pw = readline(prompt = "Enter the password: ")
for (file in file_list) {
csvfile <- gsub("\\.zip", "\\.csv", gsub(".*? ", "", file)) #csvfile name (removes output_dir from 'file' and replaces .zip extension with .csv)
#check if csvfile already exists in output_dir, and if it does, replace it with archived version and if it doesn't exist, continue to extract.
if(file.exists(csvfile)) {
sys_command = paste0("7z ", "e -o", file, " -p", pw, " Y")
} else {
sys_command = paste0("7z ", "e -o", file, " -p", pw)
}
system(sys_command)
}