rename a csv file in swift

To rename a CSV file in Swift, you can use the FileManager class which provides various methods to manage files and directories in the file system. Here's how you can rename a CSV file:

main.swift
let fileManager = FileManager.default
let currentName = "data.csv"
let newName = "new-data.csv"

do {
   try fileManager.moveItem(at: URL(fileURLWithPath: currentName), to: URL(fileURLWithPath: newName))
} catch {
   print("Error renaming file: \(error)")
}
258 chars
10 lines
  • First, create an instance of FileManager using the default property.
  • Then, specify the current name of the CSV file in a constant currentName and the new name in a constant newName.
  • Finally, use the moveItem(at:to:) method of FileManager to rename the file. This method takes two arguments - the source URL, which is the current path of the file, and the destination URL, which is the new path (with the new file name).

Note that the moveItem(at:to:) method throws an error if it fails to rename the file, so we use try and catch the error using a do-catch block to handle any errors that might occur.

gistlibby LogSnag