R: Change text in all files in a folder

Noruas :

I'm trying to change the , (comma) to . (dot) in all of my text files that are in a specific folder using R. However I don't want to manually put in the filepath each time. Instead I want to loop over all of the .TXT files in the folder, and make the change in them and then just save them again with the same name at the same place.

As of right now I have problems with the writeLines function where I tried to set the path with a changable variable, this does not seem to work, resulting in the error message:

"Error in writeLines(tx2, path = listFiles[i]) : unused argument (path = listFiles[i])"

This is my curent code draft:

folder_path <- "C:/Users/pathToMyFiles"
setwd(folder_path)
listFiles= list.files(path = "C:/Users/pathToMyFiles", pattern= "*.TXT",
           full.names = TRUE)

#print(listFiles)
#print(listFiles[1])

i=1
for (i in length(listFiles)) {
  tx  <- readLines(listFiles[i])
  tx2  <- gsub(pattern = ",", replace = ".", x = tx)
  writeLines(tx2, path = listFiles[i])
  i <- i + 1
}

When looking at the produced output all of the steps in the code seems to work, except the "writeLines" function.

I would be grateful if somebody knows a workaround this.

All the best!

N

oszkar :

Cleaning up your solution to work:

setwd('C:/Users/pathToMyFiles')

text_file_list <- list.files(pattern='*.txt')
for (text_file in text_file_list) {
  text_from_file <- readLines((text_file))
  modified_text <- gsub(',', '.', text_from_file)
  writeLines(modified_text, text_file)
}

And a loop free solution using pipe (without changing directory this time):

library(magrittr)

{text_file_list <- list.files(path='C:/Users/pathToMyFiles',
                              pattern='*.txt',
                              full.names=TRUE)} %>%
  lapply(readLines) %>%
  lapply(function(x) gsub(',', '.', x)) %>%
  {mapply(function(x, y) writeLines(x, y), ., text_file_list)}

Some comments on your code:

  1. After setwd() you do not need the path and full.names arguments in list.files(). Buy the way, it is good practice not to change directories from code, than of course you have to use those arguments (as @r2evans pointed out).
  2. You don't need i = 1 and i <- i + 1 for the for loop
  3. And where you had the error: you have to use i in 1:length(fileList). The way you have used it changed only the last file in the list.
  4. All the other changes are just cosmetics

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=391183&siteId=1