Sometimes during our data analysis process, we might need to quickly generate or modify data stored as txt files. In this tutorial we will learn how to programmatically create text files in your file system and append text to them using the R language.
Create a text file
We can use the file.create() method to create an empty file in our file system.
#R file_path = 'C:/Work_Dir/text_file.txt' file.create(file_path)
Note: Make sure to specify the file path correctly. Failing to do so will render the following error:
cannot create file '<your_file_path', reason 'No such file or directory'
Write multiple lines to the file
In order to create a new file with multiple lines you can use the following snippet. We first specify the path to the file we would like to create (#1); you’ll then define a vector consisting of strings (#2) and finally write the vector into you newly created text file object.
file_path = 'C:/Work_Dir/multi_line_text_file.txt' #1 my_txt <- c ( 'This is the first line', 'This is the second Line', 'etc' ) #2 writeLines (my_txt, file_path) #3
Append text to a file with R
Other use case is to be able to add one or multiple strings / lines / words to our existing file. Below is a snippet that you can easily use. Note the usage of the write() R function, and the fact that we used the append = TRUE parameter to indicate that the string should be added as a new line at end of the file content.
file_path = 'C:/Work_Dir/multi_line_text_file.txt' my_txt <- 'This is a line i would like to add.' write(my_txt, file_path, append=TRUE) #1
Write a vector to the file
Using a somewhat similar technique we to append text of a vector we defined (#1) into our file.
file_path = 'C:/Work_Dir/multi_line_text_file.txt' my_txt <- c('More text to add.', 'Another string from a vector') # 1 write(my_txt, file_path, append=TRUE)