R语言中批量读取多子文件夹内单个TXT文件的方法及报错(No such file or directory)排查
Hey there! Let's break down why you're hitting that error and how to fix it quickly.
The Root of the Problem
When you use list.files(path=data.path, recursive=T, pattern="*.txt"), the function returns relative file paths (like A/1.txt or B/2.txt) instead of full absolute paths. When you pass these directly to read.delim(), R looks for these files in your current working directory—not the main folder you specified. That's why it can't find them!
Plus a quick heads-up: read.delim() only reads one file at a time. Passing a vector of file paths directly won't work—you need to use a loop or apply function to read them all in bulk.
Solution 1: Use Full Absolute Paths (Recommended)
The simplest fix is to tell list.files() to return complete file paths by adding the full.names = TRUE parameter. This way, R knows exactly where each file lives without guessing.
Here's the corrected code:
data.path <- "C:/file/path/main" # Get full absolute paths to all txt files files <- list.files(path = data.path, recursive = TRUE, pattern = "*.txt", full.names = TRUE) # Read all files using lapply (returns a list of data frames) read_files <- lapply(files, read.delim, header = TRUE, sep = "\t") # If all files have the same structure, combine them into one data frame combined_data <- do.call(rbind, read_files)
If you forgot to use full.names = TRUE initially, you can also manually build the full paths later with file.path():
files <- list.files(path = data.path, recursive = TRUE, pattern = "*.txt") files <- file.path(data.path, files) # Adds the base path to each relative path
Solution 2: Switch Your Working Directory
Alternatively, you can set your working directory to the main folder first. This makes the relative paths returned by list.files() valid for read.delim():
data.path <- "C:/file/path/main" setwd(data.path) # Switch to the main folder files <- list.files(recursive = TRUE, pattern = "*.txt") read_files <- lapply(files, read.delim, header = TRUE, sep = "\t") combined_data <- do.call(rbind, read_files)
Just note that changing your working directory might affect other scripts or file operations, so the first solution is usually the safer bet.
内容的提问来源于stack exchange,提问作者Mahmoud

