Python에서 파일 경로의 일부 (디렉토리) 추출


163

특정 경로의 상위 디렉토리 이름을 추출해야합니다. 이것은 다음과 같습니다

c:\stuff\directory_i_need\subdir\file

"파일"의 내용을 directory_i_need경로가 아닌 이름 을 사용하는 것으로 수정하고 있습니다 . 모든 파일 목록을 제공하는 기능을 만든 다음 ...

for path in file_list:
   #directory_name = os.path.dirname(path)   # this is not what I need, that's why it is commented
   directories, files = path.split('\\')

   line_replace_add_directory = line_replace + directories  
   # this is what I want to add in the text, with the directory name at the end 
   # of the line.

어떻게해야합니까?


1
이 답변을 확인하고 싶을 수도 있습니다. stackoverflow.com/a/4580931/311220
— Acorn

위의 링크는 내가 잘못한 것을 고치는 방법을 이해하는 데 도움이되었습니다. 감사합니다.
— Thalia

답변:


238
import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
file
os.path.dirname(file) ## directory of file
os.path.dirname(os.path.dirname(file)) ## directory of directory of file
...

그리고 필요한만큼이 작업을 계속할 수 있습니다 ...

편집 : 에서 을 os.path , 당신도 os.path.split 또는 os.path.basename을 사용할 수 있습니다 :

dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file
## once you're at the directory level you want, with the desired directory as the final path node:
dirname1 = os.path.basename(dir) 
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.

경로의 일부를 추출하지만 경로에서 실제 디렉토리 이름을 추출하는 방법을 모르겠습니다.
— Thalia

43

Python 3.4에서는 pathlib 모듈을 사용할 수 있습니다 .

>>> from pathlib import Path
>>> p = Path('C:\Program Files\Internet Explorer\iexplore.exe')
>>> p.name
'iexplore.exe'
>>> p.suffix
'.exe'
>>> p.root
'\\'
>>> p.parts
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
>>> p.relative_to('C:\Program Files')
WindowsPath('Internet Explorer/iexplore.exe')
>>> p.exists()
True

API의 멋진 데모
— Nadim Farhat

이것은 또한 이전 버전의 Python으로 백 포트되었습니다. pathlib2
— phoenix

11

사용하면 필요한 parent부분 pathlib입니다.

from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent) 

출력합니다 :

C:\Program Files\Internet Explorer    

모든 부품이 필요한 경우 (이미 답변에 이미 포함되어 있음) 사용 parts:

p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts) 

그런 다음 목록을 얻습니다.

('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')

시간 톤을 저장합니다.


5

먼저에서 splitunc()사용할 수있는 기능 이 있는지 확인하십시오 os.path. 반환 된 첫 번째 항목은 원하는 것입니다 ...하지만 Linux에 있으며 가져 와서 os사용할 때이 기능이 없습니다 .

그렇지 않으면 작업을 수행하는 반추 한 방법 중 하나를 사용하는 것입니다.

>>> pathname = "\\C:\\mystuff\\project\\file.py"
>>> pathname
'\\C:\\mystuff\\project\\file.py'
>>> print pathname
\C:\mystuff\project\file.py
>>> "\\".join(pathname.split('\\')[:-2])
'\\C:\\mystuff'
>>> "\\".join(pathname.split('\\')[:-1])
'\\C:\\mystuff\\project'

파일 바로 위의 디렉토리와 그 바로 위의 디렉토리를 검색하는 것을 보여줍니다.


제안 사항을 수행하는 rsplit의 사용을 보여주기 위해 항목을 편집했지만 디렉토리 이름뿐만 아니라 여전히 경로를 제공합니다.
— Thalia

1
나는 아직도 당신이 무엇을 요구하는지 명확하지 않습니다. 그렇다면 다음 상위 \\ 인스턴스 왼쪽에있는 모든 것을 제거하지 않겠습니까? 경로를 원하는 것처럼 가장 한 다음 경로를 \\로 나눌 때 마지막 항목을 유지하십시오. 이게 작동해야합니까?
— ely

나는 길을 나누고 원하는 조각을 가져갔습니다. 이전에는 작동하지 않았지만이 모든 대답을 읽은 후에 내가 잘못한 것을 발견했습니다.
— Thalia

답변을 읽는 데 도움이 되었다면 최소한 투표를 통해 그 중 하나를 받아들이십시오. 그래도 오류를 발견하게되어 기쁩니다.
— ely

나는이 추한 방식이 마음에 들었습니다. 간단한 os.sep로 "\\"를 변경하면 경로의 일부만 검색 할 수 있습니다.
— TazgerO

1

이것이 내가 디렉토리의 일부를 추출하기 위해 한 것입니다.

for path in file_list:
  directories = path.rsplit('\\')
  directories.reverse()
  line_replace_add_directory = line_replace+directories[2]

도와 주셔서 감사합니다.


0
import os

directory = os.path.abspath('\\') # root directory
print(directory) # e.g. 'C:\'

directory = os.path.abspath('.') # current directory
print(directory) # e.g. 'C:\Users\User\Desktop'

parent_directory, directory_name = os.path.split(directory)
print(directory_name) # e.g. 'Desktop'
parent_parent_directory, parent_directory_name = os.path.split(parent_directory)
print(parent_directory_name) # e.g. 'User'

이것은 트릭을 수행해야합니다.


-1

os.path.split에 매개 변수로 전체 경로를 넣어야합니다. 문서를 참조하십시오 . 문자열 분할처럼 작동하지 않습니다.


Windows의 UNC 유형 경로 이름에서는 os.path 항목 상태에 대한 Python 문서처럼 작동하지 않습니다.
— ely
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.