대학원 공부/programming language
Python : basic : import OS (파일, 디렉토리 조작)
월곡동로봇팔
2019. 11. 11. 02:58
[python] 파일, 디렉터리 조작
디렉터리, 파일, 확장자 분리 (get directory and file, extension) 파일 확인 (check file exists) 파일 복사 (copying files) 파일 이동 (moving files) 파일삭제 (deleting files) 디렉터리 복사 (copying directories) 디렉터리 이동 (moving directo…
godoftyping.wordpress.com
- 디렉토리, 파일 확장자 분리 path.dirname / path.basename / split / splitext
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',
- 파일 확인
print(os.path.exists('/home/')) # True
print(os.path.exists('/home/not-exists-file')) # False
- 파일 복사
import shutil
shutil.move('a_dir', 'b_dir')
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 는 현재 경로
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)