14. Python/기초

02. 파이썬 기본 [미완성]

THE HEYDAZE 2020. 6. 6. 06:33
OS Windows 10 Home 64bit 버전 1903 (OS 빌드 18362.836)
python 3.6.0
참고 사이트
 

Python Tutorial

Python Tutorial Learning by Examples With our "Try it Yourself" editor, you can edit Python code and view the result. Click on the "Try it Yourself" button to see how it works. Python File Handling In our File Handling section you will learn how to open, r

www.w3schools.com

#1. 주석
주석 
한 줄   # 주석입니다
여러줄 (방법1)   # 주석입니다
  # 주석입니다
여러줄 (방법2)   """
  주석입니다
  주석입니다
  """

 

#2. 변수
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
= 'Hello World !'
= "Hello World !!"
= 1234
 
print(x) # Hello World !
print(y) # Hello World !!
print(z) # 1234
 
a, b, c = 'A''B''C'
 
print(a) # A
print(b) # B
print(c) # C
 
= y = c
 
print(z) # C
print(y) # C
print(c) # C
 
# -------------------------------------------------------------------------------
 
# 정상
print(x+a) # Hello World !A
 
# 오류
print(x+z) # Traceback (most recent call last): TypeError: must be str, not int
 
# 정상
print(x+str(z)) #  Hello World !1234
 
# 정상
print(x+' 정상')) #  Hello World ! 정상
 
# -------------------------------------------------------------------------------
 
# 전역 변수
 
= "바나나-전역변수"
 
def myfunc():
  v = "사과-지역변수"
  print("Python is " + v) # 사과-지역변수 
 
myfunc() # Python is 사과-지역변수
 
print("Python is " + v) # Python is 바나나-전역변수
 
# -------------------------------------------------------------------------------
 
# 글로벌 키워드 (지역변수를 전역변수를 만들기위해 앞에 global 을 붙여줌)
 
def myfunc2():
  global g 
  g = "자두-전역변수"
 
myfunc()
 
print("Python is " + g) # Python is 자두-전역변수
 
# -------------------------------------------------------------------------------
 
# 이미 선언된 전역변수를 함수또는 내장함수에서 변경하는 법
 
gv = "축구-전역변수"
 
def myfunc3():
  global gv # 축구-전역변수
  gv = "농구-전역변수"
  print("Python is " + gv) # Python is 농구-전역변수
 
myfunc()
 
print("Python is " + gv) # Python is 농구-전역변수
 
cs

 

#3. 데이터 타입
#4. 문자열
#5. Boolean
#6. 연산자
#7. Lists / Tuples / Sets / Dictionaries
#8. IF / While / For
#9. Function
#10. Lamda
#11. Array
#12. Class
#13. Inherit
#14. Iterate
#15. Module
#16. datetime
  코드 이미지 클릭
현재 날짜&시간 datetime.now()
(현재 날짜가 2020.6.7로 가정했을 때)
현재 날짜만 datetime.now().date()

또는

datetime.date(datetime.now())
현재 시간만 datetime.now().time()

또는

datetime.time(datetime.now())
날짜 지정 datetime(2020,6,6)
날짜 차이
datetime.now()-datetime(2020,6,6)
(현재 날짜가 2020.6.7로 가정했을 때)
날짜 형식 datetime.now().strftime('%Y-%m-%d')
2020.06.07 23:59:59 일요일 기준 결과 설명
%a Sun 
%A Sunday  일요일
%w 0: 일 / 1: 월 / 2: 화 / 3: 수 / 4: 목 / 5: 금 / 6: 토
%d 7 일 숫자
%b Jun 6월
%B June 6월
%m 6 월 숫자
%y 20 연도 2자리
%Y 2020 연도 4자리
%H 23 24시간 기준
%I 11 12시간 기준
%p AM/PM 오전/오후 출력
%M 59 59분
%S 59 59초
%f .737872 밀리 세컨드
%z UTC offset +0100
%Z Timezone CST
%j 159 1: 2020.01.01 / 366: 2020.12.31 (1~366 까지)
%U 23 n 주 차 (일요일 기준 )
%W 22 n 주 차 (월요일 기준)
%c Sun Jun  7 23:59:59 2020 현재 컴퓨터 기준 날짜와 시간
%x 06/07/20 현재 컴퓨터 기준 날짜만
%X 23:59:59 현재 컴퓨터 기준 시간만
%% % % 출력하기 위함

 

[유의 사항]

시간대를 유의해야함

- 참고1

더보기
[출처] https://spoqa.github.io/2019/02/15/python-timezone.html

 

 

- 참고2

더보기

 

[출처] https://brownbears.tistory.com/356

 

#17. Math
#18. Json
#19. RegEx
#20. try ~ except
#21. input()
#22. String format
#23. os
os
  현재 작업폴더   os.getcwd()
  디렉토리 변경   os.chdir('C:/Temp')

  특정경로에 대해 절대 경로 얻기   os.path.abspath(".//Scripts")

  경로 중 디렉토리명만 얻기   os.path.dirname("C:/python2020/theheydaze/Scripts/pip.exe")

  경로 중 파일명만 얻기   os.path.basename("C:/python2020/theheydaze/Scripts/pip.exe")

  경로 중 디렉토리명과 파일명을 나누어 얻기   dir, file = os.path.split("C:/python2020/theheydaze/Scripts/pip.exe")

  파일 각 경로를 나눠 리스트로 리턴하기   "C:/python2020/theheydaze\Scripts\pip.exe".split(os.path.sep)

  경로를 병합하여 새 경로 생성   os.path.join('C:/python2020', 'theheydaze')

  디렉토리 안의 파일/서브디렉토리 리스트   os.listdir("./venv/Scripts")

  파일 혹은 디렉토리 경로가 존재하는지 체크하기   os.path.exists("C:/python2020/theheydaze")

  디렉토리 경로가 존재하는지 체크하기   os.path.isdir("C:/python2020/theheydaze")

  파일 경로가 존재하는지 체크하기   os.path.isfile("C:/python2020/theheydaze/python.exe")

  파일의 크기   os.path.getsize("C:/python2020/theheydaze/python.exe")

 

위 메소드들은 경로가 존재하지 않아도 실행이 되지만

mkdir 같은 경우 해당경로가 존재하지 않을 경우 오류가 발생한다

아래의 코드는 현재날짜의 디렉토리가 존재하지 않는 경우 현재날짜의 디렉토리를 생성하는 코드이다

1
2
3
4
5
6
7
8
9
import os
from datetime import datetime
 
now = datetime.now().strftime('%Y.%m.%d')
 
if not os.path.isdir('./' + now):
    print('디렉토리 생성')
    os.mkdir(now)
 
cs

(TIP : . 1개는 현재위치를 의미하고 .. 2개는 상위폴더의 위치를 의미한다)

 

#24. shutil
shutil
디렉토리 삭제 shutil.rmtree('[경로]')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import os
import shutil
 
# 해당 경로
path = './'
 
# 삭제할 디렉토리명
deleteFileName = '2020'
 
# 해당 경로의 디렉토리들과 파일들을 리스트로 담기
files = os.listdir(path)
 
# 반복문
for file in files:
 
    # 해당 경로에 있는 디렉토리 또는 파일
    print(file)
 
    # '2020' 로 시작하면서 디렉토리인 파일을 삭제한다.
    if file.startswith(deleteFileName) and os.path.isdir(path + file):
        shutil.rmtree(path + file)
        print(' ㄴ' + file + ' 파일 삭제')
 
cs

 

os.rmdir 로 디렉토리를 삭제하려고 할 때

해당 디렉토리안에 하위 디렉토리 또는 파일이 있는경우 삭제할 수 없다

shutil.rmtree() 를 이용하면 오류 없이 지울수 있다.

 

#25. time
time
1초 대기 time.sleep(1)
1.5초 대기 time.sleep(1.5)

 

#26. sys
sys
종료 sys.exit()

exit() 와 sys.exit() 차이?

pyinstaller 로 exe 파일을 만든 후 exit() 를 할 경우 먹히지 않지만

sys.exit() 로 하면 먹힌다

#27. NumPy

'14. Python > 기초' 카테고리의 다른 글

01. 파이썬 설치  (0) 2020.06.06
00. 시작전  (0) 2020.06.06