StevenL StevenL - 1 year ago 84
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

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

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download