기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

파일 관리

내용

파일 관리

os 모듈

파이썬의 os 모듈을 사용하여 디렉토리(directory)를 조정할 수 있습니다.

함수 내용
getcwd() 현재 인터프리터가 작동되고 있는 디렉토리(Current Working Directory)를 나타냄, 문자열 형식
getcwdb() getcwd()와 동일하지만 bytes 형식으로 반환
chdir() 현재 working directory를 다른 디렉토리로 변경
listdir() working directory의 모든 하위디렉토리와 파일의 목록을 반환
mkdir() 지정된 경로에 새로운 디렉토리를 생성. 경로를 지정하지 않으면 working directory에 생성
rename(이름, 교체할 이름) 디렉토리의 이름을 교체
remove() 파일을 삭제
rmdir() 빈 디렉토리를 제거
import os
​
os  #모듈의 경로 반환
<module 'os' from 'C:\home\~\anaconda3\lib\os.py'>
#getcwd()
current=os.getcwd();current
'/home/~/python_programming'
type(current)
str
current2=os.getcwdb(); current2
b'/home/~/\xeb\xac\xb8\xec\x84\x9c/python_programming'
type(current2)
bytes
#chdir()
os.chdir("/home/~/문서")
os.getcwd()
'/home/~/문서'
#listdir()
os.getcwd()
'/home/~/python_programming'
os.listdir()
['python_programming_eng.epub',
'__pycache__',
...
'polymorphism.py',
'test1.txt']
#mkdir()
 os.getcwd()
'/home/~/test'
os.listdir()
[]
os.mkdir('subtest')
os.listdir()
['subtest']
#rename()
os.rename("subtest", "newTest")
os.listdir()
['newTest']
#remove(), rmdir()
os.listdir()
['test.txt']
os.remove("test.txt")
os.listdir()
[]
os.chdir('/~/test')
os.listdir()
['newTest']
os.rmdir("newTest")
os.listdir()
[]

rmdir()은 빈 디렉토리에서만 작동됩니다. 디렉토리내에 하위 디렉토리나 파일이 존재할 경우 이 명령은 예외를 발생시킵니다.

try:
 os.rmdir('test1')
except:
 print("내부에 내용물이 있으므로 삭제되지 않았습니다.")
내부에 내용물이 있으므로 삭제되지 않았습니다. 

os.path 모듈

os 모듈내에 있는 하위모듈로서 파일이나 폴더에 대한 정보를 알려줍니다.

함수내용
isdir() 지정된 이름이 폴더인지를 판단하여 True/False반환
지정된 이름의 폴더가 없어도 False, 그 이름이 파일이라도 False를 반환
isfile() isdir()과 유사하지만 폴더가 아닌 파일인지를 판단
exists() 파일이나 폴더가 존재하는가를 판단
getsize() 파일의 크기를 반환(byte단위로 표시), 폴더의 크기는 반환하지 못함
split() 파일과 폴더의 경로를 구분해 주는 함수
경로 중의 마지막에 존재하는 것을 분리
splitext()마지막 파일의 확장명을 따로 분리하여 반환
마지막이 폴더일 경우 분리되지 않음
join() 파일이름과 폴더 이름을 합쳐주는 함수
dirname() 경로의 폴더만을 분취하여 나타내는 함수
basename() 경로에서 파일만을 분취하여 나타내는 함수
os.path.isdir('reg_fig')
True
os.path.isdir('test.db')
False
os.path.isfile('test.db')
True
os.path.exists('test')
False
os.path.exists('test.db')
True
os.path.getsize('function_names.xlsx')
19037
os.path.getsize('c:/python')
4096
os.path.split("C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb")
 ('C:\\Users\\~\\~\\python_web', 'sys_os_module.ipnyb')
os.path.split("C:\\Users\\~\\~\\python_web\\reg_fig")[1]
'reg_fig'
os.path.splitext("C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb")
 ('C:\\Users\\~\\~\\python_web\\sys_os_module', '.ipnyb')
os.path.splitext("C:\\Users\\~\\~s\\python_web\\reg_fig")
 ('C:\\Users\\~\\~\\python_web\\reg_fig', '')
x=os.path.split("C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb")
os.path.join(x[0], x[1])
'C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb'
#폴더만을 분취하여 나타냄
os.path.dirname("C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb")
'C:\\Users\\~\\~\\python_web'
#파일이름을 분취하여 나타냄
os.path.basename("C:\\Users\\~\\~\\python_web\\sys_os_module.ipnyb")
'sys_os_module.ipnyb'

sys 모듈

설치된 파이썬에 대한 많은 정보들은 sys 모듈을 사용하여 확인할 수 있습니다. 빈번히 사용되는 함수들은 다음과 같습니다.

함수 내용
sys.builtin_module_namesimport의 명령없이 사용할 수 있는 내장 모듈을 확인
sys.path 모듈을 찾을 특정경로를 보여줌
sys.path.append 모듈을 이용하여 모듈을 찾을 경로를 첨가할 수 있다.
예) sys.path.append('/foo/bar') 이러한 경로 첨가는 PYTHONPATH 환경변수를 설정하는 것과 거의 동일하다.
import sys
sys.modules['os']
<module 'os' from 'C:\\Users\\~\\Anaconda3\\lib\\os.py'>
sys.builtin_module_names
('_abc',
'_ast',
&vellips;
'itertools',
'marshal',
'math',
&vellips;
'sys',
'time',
'winreg',
'xxsubtype',
'zlib')
sys.path
['C:\Users\~\anaconda3\python39.zip',
&vellips;
'C:\Users\~\anaconda3\lib\site-packages\win32\lib',
'C:\Users\~\anaconda3\lib\site-packages\Pythonwin']
sys.path.append('C:\\Users\\~\\~\\note\\python\\산책')
sys.path
['C:\Users\~\~\note\python\산책',
'C:\Users\~\anaconda3\python39.zip',
&vellips;
'C:\Users\~\anaconda3\lib\site-packages\win32\lib',
'C:\Users\~\anaconda3\lib\site-packages\Pythonwin']

댓글

이 블로그의 인기 게시물

[Linear Algebra] 유사변환(Similarity transformation)

유사변환(Similarity transformation) n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사행렬(similarity matrix)이 되며 행렬 A를 가역행렬 P와 B로 분해하는 것을 유사 변환(similarity transformation) 이라고 합니다. $$\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B $$ 식 2는 식 1의 양변에 B의 고유값을 고려한 것입니다. \begin{align}\tag{식 2} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align} 식 2의 행렬식은 식 3과 같이 정리됩니다. \begin{align} &\begin{aligned}\textsf{det}(B - \lambda I ) & = \textsf{det}(P^{-1}(AP – \lambda P))\\ &= \textsf{det}(P^{-1}) \textsf{det}((A – \lambda I)) \textsf{det}(P)\\ &= \textsf{det}(P^{-1}) \textsf{det}(P) \textsf{det}((A – \lambda I))\\ &= \textsf{det}(A – \lambda I)\end{aligned}\\ &\begin{aligned}\because \; \textsf{det}(P^{-1}) \textsf{det}(P) &= \textsf{det}(P^{-1}P)\\ &= \textsf{det}(I)\end{aligned}\end{align} 유사행렬의 특성 유사행렬인 두 정방행렬 A와 B는 'A ~ B' 와 같...

유리함수 그래프와 점근선 그리기

내용 유리함수(Rational Function) 점근선(asymptote) 유리함수 그래프와 점근선 그리기 유리함수(Rational Function) 유리함수는 분수형태의 함수를 의미합니다. 예를들어 다음 함수는 분수형태의 유리함수입니다. $$f(x)=\frac{x^{2} - 1}{x^{2} + x - 6}$$ 분수의 경우 분모가 0인 경우 정의할 수 없습니다. 이와 마찬가지로 유리함수 f(x)의 정의역은 분모가 0이 아닌 부분이어야 합니다. 그러므로 위함수의 정의역은 분모가 0인 부분을 제외한 부분들로 구성됩니다. sympt=solve(denom(f), a); asympt [-3, 2] $$-\infty \lt x \lt -3, \quad -3 \lt x \lt 2, \quad 2 \lt x \lt \infty$$ 이 정의역을 고려해 그래프를 작성을 위한 사용자 정의함수는 다음과 같습니다. def validX(x, f, symbol): ① a=[] b=[] for i in x: try: b.append(float(f.subs(symbol, i))) a.append(i) except: pass return(a, b) #x는 임의로 지정한 정의역으로 불연속선점을 기준으로 구분된 몇개의 구간으로 전달할 수 있습니다. #그러므로 인수 x는 2차원이어야 합니다. def RationalPlot(x, f, sym, dp=100): fig, ax=plt.subplots(dpi=dp) # ② for k in x: #③ x4, y4=validX(k, f, sym) ax.plot(x4, y4) ax.spines['left'].set_position(('data', 0)) ax.spines['right...

부분분수의 미분

내용 방법 1 방법 2 방법 3 부분분수의 미분 분수의 미분은 일정한 공식 을 적용하여 계산할 수 있습니다. 그러나 분수 자체가 단순한 표현으로 이루어지지 않았다면 미분 과정이나 결과는 매우 복잡할 수 있습니다. 만약 복잡한 분수 함수를 간단한 분수들로 분해할 수 있다면 계산이 보다 간편해질 것입니다. 이와 같이 분해된 간단한 분수들을 부분분수 라고 합니다. 예를 들어 다음 두 분수의 합을 계산해 봅니다. $$\begin{align} \frac{1}{x+1}+\frac{2}{x-1}&=\frac{x-1+2(x+1)}{(x+1)(x-1)}\\ &=\frac{3x+1}{x^2-1} \end{align}$$ 위 과정은 3개 이상의 여러 분수에서도 이루어질 수 있습니다. 또한 역으로 진행될 수 있습니다. 즉, 분수를 부분 분수로 분할할 수 있습니다. 그러나 이러한 과정은 대수분수 (분자의 가장 큰 차수가 분모의 최고의 차수보다 작은 분수)에서만 이루어질 수 있습니다. 예를 들어 $\displaystyle \frac {x^2+2}{x^2-1}$의 경우는 분자와 분모의 차수는 2차로 같습니다. 이러한 경우 다음과 같이 분리할 수 있습니다. $$\frac{x^2+2}{x^2-1}=1+\frac{3}{x^2-1}$$ 위의 식 중 $\displaystyle \frac{3}{x^2-1}$은 분자의 차수가 분모의 차수 보다 낮은 대수 분수이므로 부분 분수로 분리할 수 있습니다. 이와같이 부분 분수로 분해하는 방법은 다음과 같이 몇 가지로 구분할 수 있습니다. 방법 1 위 예의 결과 $\displaystyle \frac{3x+1}{x^2-1}$의 경우를 역으로 생각해 봅니다. 분모의 인수분해가 가능하면 그 분모의 인수에 의해 다음과 같이 분해할 수 있습니다. $$\begin{align} \frac{3x+1}{x^2-1}&=\frac{3x+1}{(x+1)(x-1)}\\ &=\frac{A}{x+1...