R Get Filename Without Extension: Methods and Examples
In this article
To get a filename without its extension in R, the most reliable and standard method is using the tools::file_path_sans_ext() function. This function specifically strips the last extension from a file path or filename, returning only the base name of the file.
Understanding tools::file_path_sans_ext()
The tools package is a base R package, meaning it comes pre-installed with every R installation and does not require a separate install.packages() call. The function file_path_sans_ext() is designed to handle the common task of removing the file extension while preserving the rest of the path. This is particularly useful when you are iterating through a directory of files and want to use the filenames as labels for plots, column names in a data frame, or as the base for saving output files with a different extension.
When you pass a character vector to this function, it identifies the final dot (.) in the string and removes everything from that dot to the end of the string. For example, if you have a file named "data_analysis.csv", the function will return "data_analysis". If the input is a full path like "C:/Users/Documents/project/results.txt", it returns "C:/Users/Documents/project/results".
Handling Full Paths vs. Base Filenames
A common point of confusion for beginners is the difference between removing an extension from a full directory path and removing it from just the filename. file_path_sans_ext() removes the extension but keeps the directory structure. If your goal is to get only the filename without the folder path and without the extension, you must combine two functions: basename() and file_path_sans_ext().
The basename() function strips the directory path and returns only the file name with its extension. By nesting this inside file_path_sans_ext(), you isolate the core name of the file. Consider the following workflow:
- Input: "/home/user/data/experiment_01.csv"
- Step 1 (basename): Returns "experiment_01.csv"
- Step 2 (file_path_sans_ext): Returns "experiment_01"
This two-step process is essential for creating clean labels. If you skip basename() and use the result of file_path_sans_ext() directly in a plot title, your title will include the entire system path, which is usually undesirable and visually cluttered.
Alternative Approaches Using Regular Expressions
While the tools package is the recommended approach, some developers prefer using regular expressions via gsub() or sub() for more complex patterns. This is useful when files have multiple extensions (like .tar.gz) and you want to remove all of them, rather than just the last one.
The file_path_sans_ext() function only removes the final extension. For a file named "archive.tar.gz", it would return "archive.tar". If you need to remove everything after the first dot, a regular expression is more appropriate. You can use sub("\..*$", "", filename), where \. matches the literal dot, and .*$ matches every character until the end of the string.
However, using regex comes with risks. If your filename contains dots that are not part of the extension (e.g., "version_1.2_data.csv"), a simple sub() targeting the first dot will truncate the filename prematurely, returning "version_1" instead of "version_1.2_data". This highlights why the dedicated tools function is safer for standard file operations.
Practical Implementation in a Loop
In real-world data science workflows, you rarely process a single file. Usually, you are dealing with a folder full of CSV or Excel files. The most efficient way to handle this is by combining list.files() with the extension removal functions. Here is a detailed breakdown of how to implement this logic:
- Use
list.files(path = "your/folder", pattern = "\.csv$", full.names = TRUE)to get a vector of all CSV files in a specific directory. Settingfull.names = TRUEis critical if the files are not in your current working directory. - Apply
basename()to the resulting vector to strip the directory paths. - Apply
file_path_sans_ext()to remove the.csvsuffix. - Store these cleaned names in a vector to use as keys or labels.
This pipeline ensures that regardless of where the data is stored on the disk, you end up with a clean list of identifiers based on the filenames. This is a standard pattern when automating the import of dozens of files into a single R list or data frame.
Common Problems and Edge Cases
There are several scenarios where standard filename stripping can lead to unexpected results. Understanding these edge cases prevents bugs in automated data pipelines.
- Hidden Files: On Unix-like systems, files starting with a dot (e.g.,
.gitignore) are hidden.file_path_sans_ext()may treat these differently or return an empty string if the only dot is at the beginning. - Files Without Extensions: If a filename does not contain a dot,
file_path_sans_ext()simply returns the original string. This is generally the desired behavior, as there is no extension to remove. - Multiple Extensions: As mentioned previously,
.tar.gzor.nii.gzfiles are common in bioinformatics and data archiving. Because these are logically a single compressed format, users often expect both extensions to vanish. Since R treats the last dot as the extension delimiter, you may need to callfile_path_sans_ext()twice or use a custom regex. - Trailing Dots: Filenames that end with a dot (though rare and often discouraged by operating systems) can cause inconsistent behavior across different versions of R or different OS environments.
Comparing tools vs. stringr for Filename Manipulation
Many R users rely on the stringr package for text manipulation. While stringr::str_remove() can be used to strip extensions, it requires the user to specify exactly what to remove. For example, str_remove(filename, "\.csv$") only works if you already know the extension is .csv.
The tools::file_path_sans_ext() function is superior for general-purpose filename cleaning because it is agnostic to the extension type. It doesn't care if the file is a .txt, .xlsx, or .parquet; it simply finds the last dot and removes the trailing characters. This makes your code more flexible and reusable across different projects where file formats might change.
Frequently Asked Questions
How do I remove only a specific extension and not others?
If you only want to remove .csv but keep .txt, you should not use file_path_sans_ext(). Instead, use gsub("\.csv$", "", filename). The $ symbol ensures that only dots at the end of the string are targeted, preventing the removal of .csv if it appears in the middle of a folder name.
Can I use this function on a whole folder of files at once?
Yes. file_path_sans_ext() is vectorized. This means if you pass it a character vector containing 100 file paths, it will return a character vector of 100 names with the extensions removed in a single operation, without needing a for loop.
What is the difference between basename() and file_path_sans_ext()?
basename() removes the directory path (e.g., "folder/file.txt" becomes "file.txt"), while file_path_sans_ext() removes the extension (e.g., "folder/file.txt" becomes "folder/file"). To get just the name, you must use both.
How do I handle files with double extensions like .tar.gz?
Because file_path_sans_ext() only removes the last extension, it will turn "data.tar.gz" into "data.tar". To remove both, you can either wrap the function in itself: file_path_sans_ext(file_path_sans_ext(x)), or use a regular expression like sub("\.(tar\.gz|gz|zip)$", "", x).
Is the tools package part of the tidyverse?
No, the tools package is a base R package. It is available immediately upon starting R and does not require the installation of tidyverse or any other external library, making it highly portable for sharing scripts.