如何解决R语言中file(file, "rt")无法打开连接的报错
问题描述
运行以下R代码读取西班牙日前市场小时价格相关CSV文件时出现报错:
path='Precios horarios mercado diario en España' ficheros <- dir(paste(path,'/marginalpdbc_2020_2022/',sep='')) dat2022 = as.data.frame(matrix(0,length(ficheros),25)) #matriz(valores,nfilas,ncolumnas) colnames(dat2022) = c("Fecha",c(1:24)) for (i in 1:length(ficheros)){ #lectura - dat es arreglando datos de cada fichero concreto dat <-read.csv(paste(path,'/marginalpdbc_2020_2022/',substr(ficheros[i],1,21),'.csv',sep=''),sep=';',header=FALSE) dat = as.data.frame(dat) dat=dat[c(-1,-length(dat[,1])),c(-length(dat[1,])+2,-length(dat[1,]))] ....
报错信息:
Warning: cannot open file 'Precios horarios mercado diario en España/marginalpdbc_2020_2022/NA.csv/NA.csv': No such file or directoryError in file(file, "rt") : cannot open the connection
Warning: cannot open file 'Precios horarios mercado diario en España/marginalpdbc_2020_2022/NA.csv/NA.csv': No such file or directoryError in file(file, "rt") : cannot open the connection
解决方案
- 修正文件名截取逻辑:错误路径出现
NA.csv,是因为substr(ficheros[i],1,21)对长度不足21字符的文件名返回NA。直接使用ficheros[i]作为文件名即可,无需截取:dat <- read.csv(paste(path,'/marginalpdbc_2020_2022/', ficheros[i], sep=''), sep=';', header=FALSE) - 只读取CSV文件:
dir()默认返回目录下所有文件,可能包含非CSV文件导致路径错误。添加pattern参数筛选CSV:ficheros <- dir(paste(path,'/marginalpdbc_2020_2022/',sep=''), pattern = "\\.csv$") - 避免重复添加后缀:原代码截取后再拼接
.csv,若原文件名已带.csv会生成xxx.csv.csv的错误路径,直接用原文件名可解决此问题。 - 验证拼接路径:循环中先打印路径确认正确性,方便排查:
file_path <- paste(path,'/marginalpdbc_2020_2022/', ficheros[i], sep='') print(file_path) dat <- read.csv(file_path, sep=';', header=FALSE)
内容的提问来源于stack exchange,提问作者S NT
相关产品推荐
相关产品推荐

