파이썬 | os.path.join() 메서드

Os 경로 모듈은 일반적인 경로 이름 조작에 사용되는 Python OS 모듈의 하위 모듈입니다. 이 기사에서는 os.path.join() 및 파일 경로를 안전하게 처리하는 방법에 대해 알아봅니다. 파이썬 OS .

Python os.path.join() 메서드 구문

통사론: os.path.join(경로, *경로)

매개변수:

  • : 파일 시스템 경로를 나타내는 경로류 객체입니다.
  • *길 : 파일 시스템 경로를 나타내는 경로류 객체입니다. 결합할 경로 구성 요소를 나타냅니다. 경로류 객체는 경로를 나타내는 문자열 또는 바이트열 객체입니다.
  • 메모: 특수 구문 *인수 (여기서 *경로)는 Python의 함수 정의에서 가변 개수의 인수를 함수에 전달하는 데 사용됩니다.

반환 유형: 이 메소드는 연결된 경로 구성 요소를 나타내는 문자열을 반환합니다.

Python의 os.path.join() 메소드

그만큼 os.path.join() Python의 메서드는 하나 이상의 경로 구성 요소를 지능적으로 결합합니다. 이 방법은 마지막 경로 구성 요소를 제외하고 비어 있지 않은 각 부분 뒤에 정확히 하나의 디렉터리 구분 기호('/')를 사용하여 다양한 경로 구성 요소를 연결합니다. 결합할 마지막 경로 구성 요소가 비어 있으면 끝에 디렉터리 구분 기호('/')가 추가됩니다.

경로 구성 요소가 절대 경로를 나타내는 경우 결합된 이전 구성 요소는 모두 삭제되고 절대 경로 구성 요소에서 결합이 계속됩니다.

os.path.join() 함수 예제 및 사용 사례

다음은 파일 경로를 결합하고 파일 경로를 안전하게 처리할 수 있는 몇 가지 예와 사용 사례입니다. 파이썬 너.

경로 구성 요소 연결

이 예에서는 'os.path.join()' 메서드를 사용하여 경로 구성 요소를 연결하여 유효한 경로를 효과적으로 구성합니다. 구성 요소를 올바르게 결합하여 플랫폼 간 호환성을 보장합니다.

파이썬3




import> os> # Path> path> => '/home'> # Join various path components> print> (os.path.join(path,> 'User/Desktop'> ,> 'file.txt'> ))> # Path> path> => 'User/Documents'> # Join various path components> print> (os.path.join(path,> '/home'> ,> 'file.txt'> ))> # Path> path> => '/User'> # Join various path components> print> (os.path.join(path,> 'Downloads'> ,> 'file.txt'> ,> '/home'> ))>

산출

/home/User/Desktop/file.txt /home/file.txt /home 

파일 읽기 및 쓰기

이 예에서는 os.path.join()> 방법은 기본 디렉터리와 파일 이름을 결합하여 완전한 파일 경로를 형성하는 데 사용됩니다. 그런 다음 생성된 경로는 이름이 지정된 파일의 내용을 읽는 데 사용됩니다. example.txt> .

예시.txt

techcodeview.com 

파이썬3




import> os> # Base directory and filename> base_dir> => '/home/user'> filename> => 'example.txt'> # Construct the full path> full_path> => os.path.join(base_dir, filename)> # Reading and writing files using the full path> with> open> (full_path,> 'r'> ) as> file> :> > content> => file> .read()> > print> (content)>

산출:

techcodeview.com 

디렉토리의 파일 나열

이 예에서는 'os.path.join()' 메서드를 사용하여 현재 작업 디렉터리에 있는 각 파일의 전체 경로를 생성합니다. 그러면 전체 경로가 인쇄되어 디렉터리에 있는 모든 파일의 포괄적인 목록을 볼 수 있습니다.

파이썬3




import> os> # Current working directory> current_dir> => os.getcwd()> # List files in the current directory> files_in_dir> => os.listdir(current_dir)> # Iterate over files and print their full paths> for> file_name> in> files_in_dir:> > file_path> => os.path.join(current_dir, file_name)> > print> (file_path)>

산출

/home/guest/sandbox/1e914974-f313-477e-a710-2057a0037607.in /home/guest/sandbox/driver /home/guest/sandbox/Solution.py 

For 루프를 사용하여 경로 반복

이 예에서는 'os.path.join()' 메서드를 루프 내에서 활용하여 나열된 각 파일 이름에 대한 전체 경로를 동적으로 생성합니다. 그런 다음 구성된 경로가 인쇄되어 각 파일의 처리를 나타냅니다.

파이썬3




import> os> # List of file names> names> => [> 'file1.txt'> ,> 'file2.txt'> ,> 'file3.txt'> ]> # Iterate over file names and process each file> for> file_name> in> names:> > file_path> => os.path.join(> '/home/user'> , file_name)> > print> (f> 'Processing file: {file_path}'> )>

산출

Processing file: /home/user/file1.txt Processing file: /home/user/file2.txt Processing file: /home/user/file3.txt