To rename a CSV file in Ruby, you can make use of the File#rename
method. It takes two arguments: the current name of the file, and the new name you want to give it.
Here's an example code snippet that demonstrates how to rename a CSV file:
main.rb411 chars20 lines
In the above code, we first declare the names of the old and new files. We then read the CSV data from the old file using CSV.read
. Next, we write the CSV data to the new file using CSV.open
. We iterate through each row in the data and output it to the new file. Finally, we use File.delete
to delete the old file, since it's no longer needed. We output a confirmation message to the console.
Note that you can replace the csv_data.each
loop with a single line of code that copies the entire contents of the old file to the new file, like this:
main.rb56 chars2 lines
This is a simpler and more efficient method, but it will only work for small files that can be read and written quickly. If you're working with large CSV files, using CSV
methods as shown in the first example may be a better choice.
gistlibby LogSnag