Running a loop for editing multiple txt files in Rstudio

I want to open multiple .txt files within RStudio and have created a loop to open these using the for function. I want to just delete the first line in each document and then save the .txt file again under the same name. I have been able to open one .txt file at a time using this script:

setwd("Document directory")
Test_data<-read.delim("File Name.txt")
colnames(Test_data)<-NULL
Test_data<-Test_data[-c(1),]
write.table(Test_data, file = "File Name 1.txt", sep = "\t",row.names = FALSE, col.names = FALSE)

AND I have been able to create the loop with this script:

library(tidyverse)
library(fs)
setwd("Document directory")
file_paths <-fs::dir_ls("Document directory")
file_paths

file_contents<- list()
#This creates a loop
for(i in seq_along(file_paths)){
file_contents[[i]]<-read.delim(
file = file_paths[[i]]
)
}
View(file_contents)

But I am unsure how to put this together to create a loop to edit each document in the folder I am working in.

Would anyone be willing to help, please?

Hi,

If you just want to remove the first line and they are all txt documents you're probably better off using readLines (and writeLines) rather than read.delim and write.table.

Example below will remove the first line from the files in the list:

list_of_file_paths <- list(path1, path2, ...)

for (file in list_of_file_paths) {
  writeLines(text = readLines(file)[-1], # take the contents minus the first line 
             con = file) # write back to the file
}

Hope that helps.

Thank you so much for the help; just a follow-up question, do I have to list all the files within the folder I am trying to loop?

You can list all the files using list.files rather than listing each file name individually if that's what you mean:

list_of_file_paths <- list.files(path = "path/to/Document directory", full.names = T)

for (file in list_of_file_paths) {
  writeLines(text = readLines(file)[-1], # take the contents minus the first line 
             con = file) # write back to the file
}

That is perfect, thank you so much, it did what I needed it to do.

I really appreciate your help!
Thank you again

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.