How to Get Just the Parent Directory Name of a Specific File

How to get just the parent directory name of a specific file

Use File's getParentFile() method and String.lastIndexOf() to retrieve just the immediate parent directory.

Mark's comment is a better solution thanlastIndexOf():

file.getParentFile().getName();

These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File). When getParentFile() is null you'll need to resort to using lastIndexOf, or use something like Apache Commons' FileNameUtils.getFullPath():

FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd

There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils class to grab the name from the result, use lastIndexOf, etc.

How do I get the parent directory in Python?

Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())

Old answer

Try this:

import os
print os.path.abspath(os.path.join(yourpath, os.pardir))

where yourpath is the path you want the parent for.

How do I get the parent directory's name only, not full path?

The simplest way to do this would be using pathlib. Using parent will get you the parent's full path, and name will give you just the last component:

>>> from pathlib import Path
>>> path = Path("/a/b/c/d/e")
>>> path.parent.name
'd'

For comparison, to do the same with os.path, you will need to get the basename of the dirname of your path. So that translates directly to:

import os

path = "C:/example/folder/file1.jpg"
print(os.path.basename(os.path.dirname(path)))

Which is the nicer version of:

os.path.split(os.path.split(path)[0])[1]

Where both give:

'folder'

As you can see, the pathlib approach is much clearer and readable. Because pathlib incorporates the OOP approach for representing paths, instead of strings, we get a clear chain of attributes/method calls.

path.parent.name

Is read in order as:

start from path -> take its parent -> take its name

Whereas in the os functions-accepting-strings approach you actually need to read from inside-out!

os.path.basename(os.path.dirname(path))

Is read in order as:

The name of the parent of the path

Which I'm sure you'll agree is much harder to read and understand (and this is just a simple-case example).


You could also use the str.split method together with os.sep:

>>> path = "C:\\example\\folder\\file1.jpg"
>>> path.split(os.sep)[-2]
'folder'

But as the docs state:

Note that knowing this [(the separator)] is not sufficient to be able to parse or
concatenate pathnames — use os.path.split() and os.path.join() — but
it is occasionally useful.

How to get parent directory name from path of a file in a Windows batch script?

I suggest following batch code for this task not using delayed expansion as not really needed and for that reason also working for files of which name or path contains one or more exclamation marks.

@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "RootDirectory=C:\EncryptedFiles"
set "DestinationDirectory=C:\DecryptedFiles"

if not exist "%DestinationDirectory%\" md "%DestinationDirectory%"
if not exist "%DestinationDirectory%\" (
echo ERROR: Failed to create directory: "%DestinationDirectory%"
echo/
pause
goto EndBatch
)

rem Get current date in format yyyyMMdd region independent.
for /F "tokens=2 delims==." %%I in ('%SystemRoot%\System32\wbem\wmic.exe OS GET LocalDateTime /VALUE') do set "FileNameDate=%%I"
set "FileNameDate=%FileNameDate:~0,8%"

for /R "%RootDirectory%" %%I in (*.csv.gpg) do for %%J in ("%%~dpI.") do gpg.exe --batch --yes --passphrase mypassword --output "%DestinationDirectory%\%%~nxJ_%FileNameDate%.csv" --decrypt "%%I"

:EndBatch
endlocal

Please read my answer on Why does %date% produce a different result in batch file executed as scheduled task? It explains very detailed the two command lines to get current date in format yyyyMMdd region independent.

For each non-hidden file found by the wildcard pattern *.csv.gpg in specified root directory or one of its subdirectories one more FOR is used to get just the name of the folder containing this file by referencing full path of the file ending always with a backslash and appending a dot to reference the directory itself. See the Microsoft documentation page Naming Files, Paths, and Namespaces.

The inner FOR determines the full qualified name of the folder containing the file which is %%~dpI without backslash at end. %%~nxJ references the string after last backslash which is the full name of the folder containing current encrypted file without path. It would be also possible to use just %%~nJ to reference the folder name if it is guaranteed that no folder contains ever a . in name which is unusual, but nevertheless possible.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • echo /?
  • endlocal /?
  • for /?
  • goto /?
  • if /?
  • md /?
  • pause /?
  • rem /?
  • set /?
  • setlocal /?
  • wmic /?
  • wmic os /?
  • wmic os get /?
  • wmic os get localdatetime /?

command to retrieve the parent directory name if file doesn'texists in child directory in linux

The pure find solution, based on this thread:

find . -mindepth 2 -maxdepth 2 -type d '!' -exec sh -c 'test -e "$1"/trans/final.txt' -- {} ';' -print | 
# remove the leading Project from path
xargs -n1 basename
  1. Find directories that are exactly two level down
  2. For each entry execute test -e <entry>/trans/final.txt - ie. check if final.txt exists
  3. If it does not '!' exist, then -print the path.
  4. The | xargs -n1 basename is used to transform ./Project/19.08 into just 19.08.

My first solution using comm and creating lists, with comments in code:

# Create an MCVE
mkdir -p Project/19.0{2,4,6,8}/{base,trans}
touch Project/19.0{2,4,6}/trans/final.txt

# Extract only unique lines from the first list
# So the folders which do not have final.txt in them
comm -23 <(
# Create a list of all Project/*/ folders
find . -mindepth 2 -maxdepth 2 |
sort
) <(
# Create a list of all Project/*/*/final.txt files
find . -mindepth 4 -maxdepth 4 -name final.txt -type f |
# Extract only Project/*/ part, so twice dirname
xargs -n1 dirname | xargs -n1 dirname |
sort
) |
# Remove the leading 'Project' name
xargs -n1 basename

Getting the parent of a directory in Bash

dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.

How to rename a file to the parent's parent folder name in batch

Could be something like this (you have to drag and drop the main folder to the batch):

@echo off

if exist "%~1" (IF not exist "%~1\" exit) else (exit)
if /i not exist "%~dp0Page" md "%~dp0Page"

pushd "%~1"
for /f "delims=" %%a in ('dir /s /b *.png') do Call :Rename "%%~a" "%%~dpa"
exit

:Rename
set Cpath=%~2
set Cpath=%Cpath:~0,-1%
For %%a in ("%Cpath%") do set Cpath=%%~dpa
set Cpath=%Cpath:~0,-1%
for %%a in ("%Cpath%") do set NName=%%~nxa
move "%~1" "%~dp0Page\%NName%%~x1"
goto :EOF

Sample Image

Get parent directory name in Node.js

Better use @danielwolf's answer instead


Use split() and pop():

path.dirname(filename).split(path.sep).pop()


Related Topics



Leave a reply



Submit