StevenL StevenL - 3 months ago 10
R Question

change .txt to .csv in R

I have been able to create a code in R to batch formate all my .txt file to .csv files using

setwd("~/Desktop/test/")
filelist = list.files(pattern = ".txt")
for (i in 1:length(filelist)){
input<-filelist[i]
output<-paste0(input, ".csv")
print(paste("Processing the file:", input))
data = read.delim(input, header = TRUE)
setwd("~/Desktop/test/done/")
write.table(data, file=output, sep=",", col.names=TRUE, row.names=FALSE)
setwd("~/Desktop/test/")
}


Works great but file still retains the .txt extension in the name
Example origninal file = "sample1.txt" and then the new file says "sample1.txt.csv" The file works as a .csv but the extra ".txt" in the file name annoys me, anyone know how to remove it from name?
thanks

Answer

You could delete the unwanted .txt:

output <- paste0(gsub("\\.txt$", "", input), ".csv")

The backslash marks the dot as literal dot (it has other meaning in regular expressions if not marked). The backslash has to be doubled because R tries to escape single backslashes. The dollar sign represents the end of the string, so only ".txt" at the end of the filename gets removed.