Loop: Convert many .txt to .csv in single director

2020-05-01 08:30发布

Probably a pretty simple answer but I've had trouble converting a bunch of .txt files to .csv files in a loop. I don't want to merge or append them, just convert 71 individual .txt files into 71 individual .csv files.

I was doing my best to refer to other questions with my code relying on this thread: create a loop: convert .txt to .csv in R

I was adapting it and this is what I have so far:

filelist = list.files(pattern = ".txt")

 for (i in 1:length(filelist)) {
  cur.input.file <- filelist[i]
  cur.output.file <- paste0(cur.input.file, ".csv") 
  print(paste("Processing the file:", cur.input.file))

  # If the input file has less than 11 rows you will reveive the error message:
  # "Error in read.table: no lines available in input")
  data = read.delim(cur.input.file, header = TRUE)
  write.table(data, file=cur.output.file, sep=",", col.names=TRUE, row.names=FALSE)
}

However, my results are coming out with:

[1] "Processing the file: filename1.txt.txt"
[1] "Processing the file: filename2.txt.txt"
[1] "Processing the file: filename3.txt.txt"
[1] "Processing the file: filename4.txt.txt"
[1] "Processing the file: filename5.txt.txt"

and the formatting is all screwed up.

Any advice/ what am I doing wrong?

Cheers and Thank you.

1条回答
放我归山
2楼-- · 2020-05-01 08:48

This is a basic solution:

filelist <- list.files(pattern = ".txt")
someVar <- lapply(filelist, function(x) { 
                            textfile <- read.table(x)
                            write.csv(textfile, 
                       file = sub(pattern = "\\.txt$", replacement = ".csv", x = x))
 })

You can always add parameters in the read.table and write.csv functions per your requirements.

Edited written file name per Gregor's comment

查看更多
登录 后发表回答