【问题标题】:How to select folders containing only one CSV file among a large number of folders?如何在大量文件夹中选择只包含一个 CSV 文件的文件夹?
【发布时间】:2017-12-01 23:00:09
【问题描述】:

我有大量文件夹,每个文件夹下都包含 csv 和 htm 文件(有些文件夹有多个 csv 文件,有些只有一个 csv 文件)。

是否可以自动筛选并获取只有一个 csv 文件的文件夹并将数据导入 R 或其他统计包?

【问题讨论】:

  • 如果你要读取的CVS文件有共同的模式,你可以使用list.filespattern参数

标签: r csv import directory


【解决方案1】:

OP 已请求在所有目录中搜索 csv 文件,但只考虑那些包含恰好一个 csv 文件的目录。应该只导入那些文件。

在 UNIX 系统上,有像 fgrep 这样的操作系统命令可能可用于此目的,但我相信下面的基本 R 解决方案应该适用于任何系统:

# define starting dir
path <- file.path("path", "to", "start", "search")
# or path <- file.path(".")
# or path <- getwd()

# find all directories, recursively, i.e., also sub-directories
dirs <- list.dirs(path, recursive = TRUE)

# search all directories for csv files, i.e., file name is ending with csv
# return result as a list with a vector of file names per list element
csv_files <- lapply(dirs, list.files, pattern = "\\.csv$", full.names = TRUE)

# pick only those list elements which contain exactly one .csv file
# and unlist to get vector of file names.
# note lenghts() gets the length of each element of a list
files_to_read <- unlist(csv_files[lengths(csv_files) == 1L])

# read selected files, return result in a list
imported <- lapply(files_to_read, data.table::fread)
# or use a different file reader, alternatively
imported <- lapply(files_to_read, readr::read_csv)

# name list elements to identify imported data sets
setNames(imported) <- files_to_read
# or use only the file name
setNames(imported) <- basename(files_to_read)
# or use only the name of the enclosing directory
setNames(imported) <- basename(dirname(files_to_read))

【讨论】:

    【解决方案2】:
    getwd()
    all_files<-list.files()
    split_all_files<-sapply(all_files,function(x) strsplit(x, "\\.")[1])
    
    for(i in seq(1,length(all_files))){
    
      if(split_all_files[[i]][2]=="csv"){
        data_file<-data.frame()
        data_file<-read.csv(all_files[i])
    
       }  
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-08
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      相关资源
      最近更新 更多