First let’s load the library:
library(filesstrings)
#> Loading required package: stringr
I find it bizarre that base R has no file.move
. To move a file, you have to unintuitively rename it. filesstrings
provides file.move(files, destinations)
. This function has the nice feature that if you try to move files to a directory that doesn’t exist, it creates the directory first and then puts the files inside. Let’s create a directory and a file:
dir.create("tmp_dir")
file.create("tmp.txt")
#> [1] TRUE
Now let’s put the file into the directory:
file.move("tmp.txt", "tmp_dir")
#> 1 files moved. 0 failed to move.
To delete directories with base R, one has to use unlink(..., recursive = TRUE)
. The filesstrings
package gives you dir.remove()
which does the same job.
dir.remove("tmp_dir")
#> 1 directories deleted. 0 failed to delete.
“A space in your file name is a hole in your soul.” - Jenny Bryan
RemoveFileNameSpaces(replace.with = "_")
replaces them all with underscores for all files in a directory. By default, they are replaced with nothing.
file.create(c("file 1.txt", "file 2.txt"))
#> [1] TRUE TRUE
RemoveFileNameSpaces(pattern = "txt$", replace.with = "_")
#> 2 files renamed. 0 failed to rename.
list.files(pattern = "txt$")
#> [1] "file_1.txt" "file_2.txt"
file.remove(list.files(pattern = "txt$")) # clean up
#> [1] TRUE TRUE
The microscope I use numbers files with 3 numbers by default, i.e. file001.tif
, file002.tif
and so on. This is a problem when the automatic numbering passes 1000, whereby we have file999.tif
, file1000.tif
. What’s the problem with this? Well, sometimes you need alphabetical order to reflect the true order of your files. These file numbers don’t satisfy this requirement:
file.names <- c("file999.tif", "file1000.tif")
sort(file.names)
#> [1] "file1000.tif" "file999.tif"
so file1000.tif
comes before file999.tif
in alphabetical order. The function NiceNums
returns the names that we’d like them to have:
NiceNums(file.names)
#> [1] "file0999.tif" "file1000.tif"
The function NiceFileNums
applies such renaming to all the files in an entire directory. It wraps NiceNums
.
BeforeLastDot("spreadsheet_92.csv")
#> spreadsheet_92.csv
#> "spreadsheet_92"
Add a file extension if needed:
GiveExt("xyz", "csv")
#> [1] "xyz.csv"
If the file name has the correct extension already, it’s left alone:
GiveExt("xyz.csv", "csv")
#> [1] "xyz.csv"
Change a file extension:
GiveExt("abc.csv", "txt") # tack the new extension onto the end
#> [1] "abc.csv.txt"
GiveExt("abc.csv", "txt", replace = TRUE) # replace the current extension
#> [1] "abc.txt"