아미(아름다운미소)

[python] 파일, 디렉터리 조작 본문

랭귀지/PYTHON

[python] 파일, 디렉터리 조작

유키공 2018. 1. 11. 13:00

[python] 파일, 디렉터리 조작

디렉터리, 파일, 확장자 분리 (get directory and file, extension)
import os
 
fullpath = '/home/aaa/bbb/ccc.txt'
print(os.path.dirname(fullpath)) # '/home/aaa/bbb'
print(os.path.basename(fullpath)) # 'ccc.txt'
print(os.path.split(fullpath)) # ('/home/aaa/bbb', 'ccc.txt')
print(os.path.splitext(fullpath)) # ('/home/aaa/bbb/ccc', '.txt')

파일 확인 (check file exists)
print(os.path.exists('/home/') # True
print(os.path.exists('/home/not-exists-file') # False

파일 복사 (copying files)
import shutil
 
shutil.copy('a.txt', 'a-copied.txt')

파일 이동 (moving files)
import shutil
 
shutil.move('a.txt', 'b.txt')

파일삭제 (deleting files)
import os
 
os.remove('a.txt')

디렉터리 복사 (copying directories)
import shutil
 
shutil.copytree('src_dir', 'tar_dir')

디렉터리 이동 (moving directories)
import shutil
 
shutil.move('a_dir', 'b_dir')

디렉터리 삭제 (deleting directories)
import shutil
 
shutil.rmtree('a_dir')

디렉터리 탐색 (searching directories)
import os
 
cwd = os.getcwd()
print('current working dir: %s' % cwd)
 
for filename in os.listdir(cwd):
    fullpath = os.path.join(cwd, filename)
    if (os.path.islink(fullpath)):
        print('link: %s' % fullpath)
    elif (os.path.isfile(fullpath)):
        print('file: %s' % fullpath)
    elif (os.path.isdir(fullpath)):
        print('dir: %s' % fullpath)

os.getcwd()를 하면 현재 작업 중인 디렉터리 경로를 리턴합니다. os.listdir(dirpath) 코드를 이용해서 파일과 디렉터리 내용을 가져올 수 있습니다. 디렉터리명과 파일명을 os.path.join(dirpath, filename) 형태로 사용하면 디렉터리명과 파일명을 조합한 전체 경로를 쉽게 얻을수 있습니다. 디렉터리 탐색 (하위 디렉터리 포함)
import os
 
cwd = os.getcwd()
 
for (path, dirs, files) in os.walk(cwd):
    for f in files:
        fullpath = os.path.join(path, f)
        print(fullpath)

os.walk(dirpath)는 전달된 경로뿐만 아니라 해당 경로의 하위에 있는 모든 디렉터리 정보까지 제공해 줍니다.


Comments