简体   繁体   中英

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

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM