티스토리 뷰
import os
>>디렉토리 변경 및 확인<<
-. getcwd()
현재 작업디렉토리 반환
>>> os.getcwd()
'c:\\Python32'
-. chdir(path)
작업디렉토리 변경
>>> os.chdir("test")
>>> os.getcwd()
'c:\\Python32\\test'
-. listdir(path)
해당경로(path)에 존재하는 파일과 디렉토리를 리스트로 반환
# “.”일경우 현재디렉토리 반환
>>> os.listdir(".")
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'tcl', 'test', 'test.db', 'Tools', 'w9xpopen.exe']
-. access(path,mode)
입력받은 path에 대해서 mode에 해당하는 작업이 가능한지의 여부를 반환
F_OK : 해당 path의 존재여부를 확인하는 mode
R_OK: 해당 path의 읽기 가능여부를 확인하는 mode
W_OK: 해당 path의 쓰기 가능여부를 확인하는 mode
X_OK: 해당 path의 실행가능여부를 확인하는mode
>>디렉토리 생성 및 제거<<
-. mkdir(path [,mode])
디렉토리 생성
>>> os.mkdir("mkdirtest")
>>> os.listdir(".")
['mkdirtest']
-. makedirs(path[,mode])
디렉토리 순차적 생성
#이미 디렉토리가 있는경우나 권한이 없는경우 예외발생
>>> os.listdir(".")
['mkdirtest', 'test1']
#C:\Python32\test\test1\test2\test3\test4 생성된 디렉토리
-. rmdir(path)
빈 디렉토리 삭제
#디렉토리 안에 빈디렉토리가 있어도 삭제 불가
>>> os.rmdir("test")
-. removedirs(path)
빈 디렉토리 순차적 삭제
#rmdir과 비슷
>>> os.removedirs("aa/bb/cc")
cc디렉토리 지운후 bb지우고 aa를 지움
>>파일 관리<<
-. remove(path), unlink(path)
파일 삭제
>>> os.remove("test.txt")
>>> os.unlink("test.txt")
-. rename(a,b)
a를 b로 이름변경, a와 b가 다른 경로면 이동(이름변경하면서 이동도 가능) #디렉토리 생성은 불가
#파일, 디렉토리 모두 가능
>>> os.rename("test.txt","test2.txt") #같은 디렉토리 이므로 이름만 변경됨
>>> os.rename("test.txt","data/test2.txt") #data 디렉토리로 이동과 함께 파일이름 변경
-. renames(a,b)
a를 b로 이름변경, a와 b가 다른 경로면 이동(이름변경하면서 이동도 가능) #디렉토리 생성 가능
#파일, 디렉토리 모두 가능
>>> os.renames("test.txt","test2.txt") #같은 디렉토리 이므로 이름만 변경됨
>>> os.renames("test.txt","data/test2.txt") #data 디렉토리로 이동과 함께 파일이름 변경
-. stat(path)
경로에 해당하는 정보를 반환
>>> os.stat(".")
nt.stat_result(st_mode=16895, st_ino=1407374883559076, st_dev=0, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1353267245, st_mtime=1353267245, st_ctime=1352382813)
>>> os.stat("test.txt")
nt.stat_result(st_mode=33206, st_ino=2533274790427368, st_dev=0, st_nlink=1, st_uid=0, st_gid=0, st_size=0, st_atime=1353266985, st_mtime=1353266985, st_ctime=1353266985)
-. utime(path,times)
경로에 해당하는 파일에 액세시시간,수정시간을 times로 수정
#times가 None일경우 현재시간으로 수정됨
>>> os.utime("test.txt",None) #파일의 액세스시간과 수정시간을 현재시간으로 변경
>>> os.utime("test.txt",(1,1)) #파일의 액세스시간과 수정시간을 [19700101 09:00:01]로 변경
-. walk(top[,topdown=True[,onerror=None[,followlinks=False]]])
top으로 지정된 디렉토리를 순회하며 경로, 디렉토리명을 순차적으로 반환
- test
+-intest.txt
+-game
+-ingame.txt
+-music
+-inmusic.txt
위와 같은 디렉토리 구조에서 해당명령어 사용시
>>> for path,dirs,files in os.walk('test'):
print(path,dirs,files)
test ['game'] ['intest.txt']
test\game ['music'] ['ingame.txt']
test\game\music [] ['inmusic.txt']
-. umask(mask)
umask를 설정, 수행시 이전mask값 반환
umask가 수행되면 이후 오픈되는 파일이나 디렉토리에 (mode & ~umask)와 같이 적용됨
-. pipe()
※ from os import * 사용시 import 안됨, from os import fdopen 가능 혹은 os.fdopen으로 사용가능
파이프생성, 함수를 실행하면 읽기, 쓰기 전용 파이프의 파일 디스크립터가 반환됨
파이프는 주로 부모프로세스와 자식프로세스간의 통신을 목적으로 사용함
>>> os.pipe()
(3, 4)
-. fdopen(fd[,mode[,bufsize]])
파일 디스크립터를 이용해 파일 객체를 생성
>>> r,w = os.pipe()
>>> rd = os.fdopen(r)
>>> rd
<_io.TextIOWrapper name=3 mode='r' encoding='cp949'>
-. popen(command[,mode[,bufsize]])
※ from os import * 사용시 import 안됨, from os import popen 가능 혹은 os.popen으로 사용가능
인자로 전달된 command를 수행하며 파이프를 염
#Python3에서는 Popen클래스의 사용을 권장하지만 그대로 사용할수도 있음
>>> p=os.popen('dir','r')
>>> p.read()
' D 드라이브의 볼륨에는 이름이 없습니다.\n 볼륨 일련 번호: 1CF0-1B89\n\n D:\\Cloude\\Python\\new 디렉터리\n\n2012-11-19 오전 05:01 <DIR> .\n2012-11-19 오전 05:01 <DIR> ..\n2012-11-09 오전 12:23 <DIR> chapter7\n2012-11-19 오전 05:01 <DIR> d\n2012-11-19 오전 05:00 31 osmodule.py\n2012-11-16 오후 04:56 2,138 pingtest.py\n2012-11-19 오전 04:53 <DIR> test\n2012-11-12 오후 04:12 2,049 test.py\n1938-04-25 오전 07:13 0 test.txt\n2012-11-17 오전 08:46 90 tt.py\n2012-11-17 오전 08:37 <DIR> __pycache__\n2012-11-17 오전 06:44 363 다중상속.py\n 6개 파일 4,671 바이트\n 6개 디렉터리 79,014,903,808 바이트 남음\n'
#cmd창에서 dir사용시 출력된 내용
>>그밖의 기능<<
-. system(command)
command를 실행하여 성공하면 0을 반환
>>> os.system("notepad") #메모장 실행
0 #실행된 메모장을 종료하면 값 반환
-. startfile(path[,operation])
path를 os에서 지정된 프로그램으로 실행, operation으로 명시적으로 수행할 프로그램 지정
>>> os.startfile("test.txt") #test.txt파일을 실행함
※ os.system은 Python프로그램을 멈추고 파일 실행하지만 os.startfile은 Python을 멈추지 않고 파일 실행함
-. exec...
execl(path,arg0,arg1,...)
execle(path,arg0,arg1,...,env)
execlp(file,arg0,arg1,...)
execlpe(file,arg0,arg1,...,env)
execv(path,args)
execve(path,args,env)
execvp(file,args)
execvpe(file,args,env)
l = 입력인자들의 수가 정해져 있는 경우
v = args라는 튜플로 입력인자를 받음
e = 환경변수 env를 받느냐 아니냐의 차이
p = 환경변수 path를 이용하는 경우
>>>os.execl('c:\python32\python','python','-v')
>>>os.execv('python',('python','-v'))
>>>os.execle('c:\python32\python','python','-v',{"HOME":"c:\\"})
-. name
Python이 실행되는 운영체제의 이름을 나타냄(nt,posix,max등)
>>> os.name
'nt'
-. getpid()
현재 pid값 반환
>>> os.getpid()
652
-. environ
환경변수들을 나타내는 사전
homepath,userprofile등의 정보 확인 가능
>>> os.environ
environ({'TMP': 'C:\\DOCUME~1\\ADMINI~1\\LOCALS~1\\Temp', 'COMPUTERNAME': 'YOUNGJAE-HWANG-', 'USERDOMAIN': 'YOUNGJAE-HWANG-', 'PSMODULEPATH': 'C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\Modules\\', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'PROCESSOR_IDENTIFIER': 'x86 Family 6 Model 37 Stepping 5, GenuineIntel', 'PROGRAMFILES': 'C:\\Program Files', 'PROCESSOR_REVISION': '2505', 'SYSTEMROOT': 'C:\\WINDOWS', 'HOME': 'C:\\Documents and Settings\\Administrator', 'TK_LIBRARY': 'C:\\Python32\\tcl\\tk8.5', 'TEMP................................
>>> os.environ['homepath']
'\\Documents and Settings\\Administrator'
>>> os.environ['userprofile']
'C:\\Documents and Settings\\Administrator'
>>>
-. getenv(varname[,value])
환경변수의 값을 얻어옴
해당환경변수가 없을 경우 인자로 전달된 value값을 반환
해당환경변수가 없고 value가 생략된경우 None 반환됨
>>> os.getenv('PYTHONPATH',"not found")
';D:\\Cloude\\Python\\lib2;'
>>> os.getenv('PYTHONPATH2',"not found")
'not found'
-. putenv(varname,value)
환경변수 varname을 value로 설정, 자식프로세스에게 영향을 미침
>>> os.putenv("test","\\tmp\\test")
>>> p = os.popen('''python -c "import os;print(os.getenv('test'))"''','r')
>>> p.read()
'\\tmp\\test\n'
-. strerror(code)
에러코드에 해당하는 에러메시지를 보여줌
>>> os.strerror(0)
'No error'
>>> os.strerror(1)
'Operation not permitted'
>>> os.strerror(2)
'No such file or directory'
'Python' 카테고리의 다른 글
Python, 2와 3의 차이 (0) | 2016.04.21 |
---|---|
Python,module sys (0) | 2016.04.21 |
Python, Class (0) | 2016.04.21 |
Python, join (0) | 2016.04.21 |
Python, map() (0) | 2016.04.21 |
- Total
- Today
- Yesterday
- 폼
- vba
- JPA
- 리눅스
- borderwidth
- fetch join
- activebackground
- indicatoron
- disabledforeground
- ManyToOne
- tkinter
- Python
- 파이썬
- IdClass
- Java
- onetomany
- 상수
- apache
- activeforeground
- highlightthickness
- checkbutton
- Module
- Private
- tkinter command & bind [명령어묶기와 사건묶기] Python
- Composite Key
- Linux
- Excel
- FetchType
- command
- highlightbackground
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |