Python : OS module Tutorial

Joey Lee·2020년 12월 10일
0

Python

목록 보기
12/12

The os module allows us to access functionality of the underlying operating system. So we can perform tasks such as: navigate the file system, obtain file information, rename files, search directory trees, fetch environment variables, and many other operations.

import os

# 현재 사용중 디렉토리
os.getcwd()

# 현재 사용 중인 디렉토리 바꾸기
os.chdir('/Users/seungho')

# 현재 디렉토리 아래 디렉토리 리스트 보기
os.listdir()

# 디렉토리 만들기
os.mkdir('OS-Demo-2')

# sub 디렉토리 만들기
os.makedirs('OS-Demo-2/Sub-Dir-1')

# 디렉토리 삭제하기
os.rmdir('OS-Demo-2/Sub-Dir-1')
os.removedirs('OS-Demo-2/Sub-Dir-1')

# 파일 네임 바꾸기
os.rename('mydoc.pdf', 'demo.pdf')

# 파일 속성 보기
os.stat('demo.pdf')
> os.stat_result(st_mode=33188, st_ino=42712025, st_dev=16777222, st_nlink=1, st_uid=501, st_gid=20, st_size=1424, st_atime=1604490708, st_mtime=1592543808, st_ctime=1607604055)

from datetime import datetime
print(os.stat('demo.pdf').st_mtime)
> 1592543808.4475832

# timestamp를 datetime 형식으로 변환
mod_time = os.stat('demo.pdf').st_mtime
print(datetime.fromtimestamp(mod_time))
> 2020-06-19 14:16:48.447583

# 디렉토리의 모든 트리구조를 보고 싶을 때, os.walk()
for dirpath, dirnames, filenames in os.walk('/Users/seungholee/web_crawling'):
    print('Current Path:', dirpath)
    print('Directories:', dirnames)
    print('Files:', filenames)
    print()

# 홈 디렉토리 가져오기
print(os.environ.get('HOME'))

'test.txt'

# 경로와 파일 => 합친 경로 뽑아내기
file_path = os.path.join(os.environ.get('HOME'),'test.txt')
print(file_path)
> /Users/seungholee/test.txt

# os.path의 주요 메소드 살펴보기
print(os.path.basename('/tmp/test.txt'))
> test.txt
print(os.path.dirname('/tmp/test.txt'))
> /tmp
print(os.path.split('/tmp/test.txt'))
> ('/tmp', 'test.txt')
print(os.path.exists('/tmp/test.txt'))
> Flase

print(dir(os.path))
> ['__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_get_sep', '_joinrealpath', '_varprog', '_varprogb', 'abspath', 'altsep', 'basename', 'commonpath', 'commonprefix', 'curdir', 'defpath', 'devnull', 'dirname', 'exists', 'expanduser', 'expandvars', 'extsep', 'genericpath', 'getatime', 'getctime', 'getmtime', 'getsize', 'isabs', 'isdir', 'isfile', 'islink', 'ismount', 'join', 'lexists', 'normcase', 'normpath', 'os', 'pardir', 'pathsep', 'realpath', 'relpath', 'samefile', 'sameopenfile', 'samestat', 'sep', 'split', 'splitdrive', 'splitext', 'stat', 'supports_unicode_filenames', 'sys']
profile
안녕하세요!

0개의 댓글