Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract only folder name right before filename from full path

I have the following path

filePath <- "/data/folder1/subfolder1/foo.dat"

I'd like to get subfolder1 which is where foo.dat locates. I saw solutions in other languages but haven't found one in R. What is the simplest way to do it? Thank you!

What I tried

> basename(filePath)
[1] "foo.dat"

> dirname(filePath)
[1] "/data/folder1/subfolder1"
like image 676
IloveCatRPython Avatar asked Nov 08 '17 20:11

IloveCatRPython


People also ask

Does full path include filename?

Paths include the root, the filename, or both. That is, paths can be formed by adding either the root, filename, or both, to a directory.

How can I get a directory name?

dirname() to get the directory folder (name) from a path string. If you want to get only the directory name directly above the file, use os. path. basename() .

How do you remove a filename from a path in Python?

Use os.remove() function to delete File The OS module in Python provides methods to interact with the Operating System in Python. The remove () method in this module is used to remove/delete a file path.


2 Answers

This may solve:

filePath <- "/data/folder1/subfolder1/foo.dat"

basename(dirname(filePath))

http://www.r-fiddle.org/#/fiddle?id=IPftVEDk&version=1

like image 185
Falci Avatar answered Oct 21 '22 05:10

Falci


This may not be the prettiest answer, but it will work for you:

unlist(strsplit(filePath, '/'))[length(unlist(strsplit(filePath, '/')))-1]
like image 23
Dan Raps Avatar answered Oct 21 '22 03:10

Dan Raps