Home > Enterprise >  How to add a new line in multiple existing csv files using R?
How to add a new line in multiple existing csv files using R?

Time:03-29

I want to read multiple csv files into R, but the csv files don't en with a new line. When I try to read csv files i get this error message "Files must end with a newline" so in order to fix that for one single csv file this code which works fine:

# Add blank row
blank <- ""

# csv file name
csv_name <- "testfile.csv"

# writing row in the csv file
write.table(blank, file = csv_name, sep = ";",
            append = TRUE, quote = FALSE,
            col.names = FALSE, row.names = FALSE)

But I don’t know how to scale this when I have multiple csv files (in the same folder) and all the files have the same problem: they don’t end with a new line. I have tried but failed to find a good way to write a loop or to use purrr map functions. A suggestion would be much appreciated!

CodePudding user response:

If you really want to use R for this task, you could use

my_path <- "."

my_csv_list <- list.files(path = my_path, pattern = ".csv$")

blank <- ""

for (file in my_csv_list) {
  write.table(blank, file = file, sep = ";",
              append = TRUE, quote = FALSE,
              col.names = FALSE, row.names = FALSE)
}

or instead of a for-loop

sapply(my_csv_list, 
       function(file) 
         write.table(blank, file = file, sep = ";",
                     append = TRUE, quote = FALSE,
                     col.names = FALSE, row.names = FALSE))

Just set my_path to the path containing your .csv-files. file.path could be useful for this.

  •  Tags:  
  • r csv
  • Related