랭귀지/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')
print(os.path.exists('/home/') # True
print(os.path.exists('/home/not-exists-file') # False
import shutil
 
shutil.copy('a.txt', 'a-copied.txt')
import shutil
 
shutil.move('a.txt', 'b.txt')
import os
 
os.remove('a.txt')
import shutil
 
shutil.copytree('src_dir', 'tar_dir')
import shutil
 
shutil.move('a_dir', 'b_dir')
import shutil
 
shutil.rmtree('a_dir')
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)
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)는 전달된 경로뿐만 아니라 해당 경로의 하위에 있는 모든 디렉터리 정보까지 제공해 줍니다.