Suusie
Suusie

Reputation: 149

Get name of file in read.csv same as in write.csv

I would like to achieve that the file I write.csv has the same name as the file I use with read.csv2. See below: I am reading a file name "2005Calc.csv" and want to write it as: "2005Calc28-01-2021.csv". How can I do this? I tried something below and it works..only I am not able to add the csv file name to it.

Thank you in advance.

    LKCalc <- read.csv2("2005Calc.csv")

    date<-format(Sys.time(), "%d-%m-%Y")

    csvFileName <- paste("FILENAME",date,".csv",sep="")

    write.csv(LKCalc, file=csvFileName) 

Upvotes: 0

Views: 1040

Answers (3)

Matt
Matt

Reputation: 7415

Here is a solution without having to provide a name:

# Read in your data
LKCalc <- read.csv2("C:/YOUR PATH.csv")

# Create date character vector
date<-format(Sys.time(), "%d-%m-%Y")

# Pull names from the path you specify (this should be where your document(s) live)
# If you have more than one .csv, you will need to iterate over names, or figure out a way to modify.
# This is only to illustrate how this might be done
name <- list.files(path = "C:", pattern = ".csv")

# Remove ".csv" from the name
name <- sub(".csv$", "", name)

# Create the file name
csvFileName <- paste0(name,date,".csv")

# Write out
write.csv(LKCalc, file=csvFileName) 

Upvotes: 1

Ben Bolker
Ben Bolker

Reputation: 226732

"FILENAME" is a literal string, not a variable referring to a file name. How about (untested):

FILENAME <- "2005Calc"
LKCalc <- read.csv2(paste0(FILENAME,".csv"))
date <- format(Sys.time(), "%d-%m-%Y")
csvFileName <- paste0(FILENAME,date,".csv")
write.csv(LKCalc, file=csvFileName) 

Upvotes: 1

mhovd
mhovd

Reputation: 4087

The function list.files()(documentation) will give you the filename of all files that match a given pattern (or all if not supplied).

Upvotes: 1

Related Questions