Reputation: 99
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
Upvotes: 4
Views: 23261
Reputation: 3843
write.table(filelist,file=paste0("~/Desktop/test/done/",sub(".txt","",filelist[i]),".csv"),row.names=F,colnames=T,quote=F,sep=",")
Alternative help:
setwd("~/Users/Rio/Documents/Data/")
FILES <- list.files( pattern = ".txt")
for (i in 1:length(FILES)) {
FILE=read.table(file=FILES[i],header=T,sep="\t")
write.table(FILE,file=paste0("~Users/Rio/Documents/Data/",sub(".txt","",FILES[i]),".csv"),row.names=F,quote=F,sep=",")
}
Upvotes: 1
Reputation: 18450
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.
Upvotes: 6