You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言中批量读取多子文件夹内单个TXT文件的方法及报错(No such file or directory)排查

Fixing the "No such file or directory" Error in R When Reading Multiple TXT Files

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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:42:29