【问题标题】:Renaming multiple files with multiple names用多个名称重命名多个文件
【发布时间】:2020-11-14 21:24:52
【问题描述】:
setwd("C:\\Users\\...\\Documents\\Main\\eml orders") 

files <- list.files(pattern="*.eml")

newfiles <- gsub(".eml$", ".txt", files)

file.rename(files, newfiles)

eml_files <- list.files(pattern = "txt$")

我有这段代码可以将 .eml 转换为 .txt 文件,现在我想将相同的文件重命名为我使用函数创建的字符串。

函数示例

fetch_date <- function(x) {
date <- paste0(as.character(Sys.time()), ".txt")
file.rename(x, date)
}

现在我试试map(eml_files, fetch_date)

并得到这个错误:

cannot rename file '24 New order placed.txt' to '2020-11-14', reason 'The network path was not found'

不知道发生了什么任何帮助将不胜感激。

【问题讨论】:

  • 你可能需要full.names = TRUE in list.files
  • 同样的错误:/ .
  • 函数内部,可能需要用file.path指定路径
  • 我在函数内部做了file.path("C:\\Users\\...\\Documents\\Main\\eml orders"),但它仍然无法正常工作。抛出相同的错误。
  • 您的 file.rename 似乎在函数之外工作。你有没有试过不带函数的第二组重命名

标签: r tidyverse purrr stringr


【解决方案1】:

请注意,您的 fetch_date 函数仅输出一个字符串 (Sys.date())。它尝试用相同的名称命名多个.txt 对象。在我的 Mac 上,这会导致最后一个文件被保留,而其他文件被覆盖。也许您使用的是 Windows,当文件被覆盖时还有另一种默认行为?

eml_files <- list.files(pattern = "txt$")


fetch_date <- function(x) {
  date <- paste0(as.character(Sys.time()), ".txt")
  file.rename(x, date)
}


map(eml_files, fetch_date)

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 2015-10-23
    • 2019-11-13
    • 2014-01-26
    • 1970-01-01
    • 2017-06-23
    • 2022-06-14
    相关资源
    最近更新 更多