开发者

How to get rid of file extensions (.CSV) in a file name that is generated by R

开发者 https://www.devze.com 2023-03-05 02:45 出处:网络
I have a series of .csv files in my working folder and I wrote a code to get them all, do everything I want to do with them and, in the end, write the result in another file adding \"_pp\" to the orig

I have a series of .csv files in my working folder and I wrote a code to get them all, do everything I want to do with them and, in the end, write the result in another file adding "_pp" to the original file name:

random <- grep(".csv",list.files(), fixed=TRUE)                             
files <- list.files()[random]   
for (igau in 1:length(files))                                               
{
(.......)
file <- pas开发者_C百科te("H:/METEO_data/AEMET_2/",files[igau],"_pp.csv",sep="")
write.table(d,file,row.names=TRUE, col.names=NA, sep=" ")                   
}

the problem is that I get "3059.csv_pp.csv" when what I wanted was "3059_pp.csv". Is there a way of taking the first .csv out?

thanks


Your first two lines can be simplified to one list.files call that uses the pattern argument. Then you can change the output file name using gsub.

files <- list.files(pattern=".csv")
for(i in 1:length(files)) {
  outFile <- file.path("H:/METEO_data/AEMET_2",
                       gsub(".csv", "_pp.csv", files[igau]))
  write.table(d, outFile, row.names=TRUE, col.names=NA, sep=" ")
}

You could also loop over the elements in files, but that assumes you don't need the igau index for anything else. And in order to potentially avoid confusing yourself in the future, you may want to avoid using file for variable names because it's base package function that opens a connection to a file.

for(File in files) {
  outFile <- file.path("H:/METEO_data/AEMET_2",
                       gsub(".csv", "_pp.csv", File))
  write.table(d, outFile, row.names=TRUE, col.names=NA, sep=" ")
}


The problem is that files[igau] contains the .csv extension. You'll have to do something like this:

basefile <- strsplit(files[igau], ".")
file <- paste("H:/METEO_data/AEMET_2/",basefile[0],"_pp.csv",sep="")

basefile[0] will contain everything before the first .. This means that this code will break if you have filenames with dots in them (i.e. 3059.2.csv). If this is the case, then you'll have to paste() together everything in basefile except for the last element, which will be the csv that you're trying to get rid of.

0

精彩评论

暂无评论...
验证码 换一张
取 消