파일 읽기 및 쓰기

 

 

 

 

 

읽기 모드 : r, 쓰기모드 w, 추가 모드 a(append), 텍스트 모드(기본값,생략가능) t, 바이너리 모드 b
상대 경로('../<상위폴더>, ./<현재폴더>'), 절대 경로('C:\Django\example..')

##파일 Write 실습(1)
'''
open함수 설명
Mode 설명
다양한 읽기(read) 방법
다양한 쓰기(write) 방법
입출력 중요 설명
'''

 

 

 

주의!

import os

print(os.getcwd())가 자신이 작업하고 있는 폴더를 정확히 가리키고 있는지 확인해야한다!

만약 그렇지 않으면 상대경로가 파일을 찾지 못한다!

 

C:\Users\Jaesang Choi\Desktop\python_basic

 

 

 


# 파일 읽기(Read)

 


# 예제1

f = open('./resource/it_news.txt', 'r', encoding='UTF-8') #rt라고 해도 된다. t는 기본값이라 빼도 됨
# 속성 확인
print(dir(f)) #['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__'...]
# 인코딩 확인
print(f.encoding) #UTF-8
# 파일 이름
print(f.name) #./resource/it_news.txt
# 모드 확인
print(f.mode) #r
cts = f.read()
print(cts)
Right now gamers can pay just $1 for access to hundreds of titles across PC
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont
activate that insanely cheap one-month trial just yet. You can lock in up to
three years of Xbox Game Pass Ultimate with that same dollar if you play
your cards right.
When you activate Microsoft��s E3 2019 promotion, it not only begins the trial,
but also converts existing Xbox Live Gold and standard Xbox Game Pass
subscriptions on your account to Game Pass Ultimate (normally $15 per
month). Any prepaid time up to the maximum of three years gets the upgrade.
# 사용한 후에는 반드시 close!
f.close()

 



# 예제2

with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
c = f.read()
print(c)
Right now gamers can pay just $1 for access to hundreds of titles across PC
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont
activate that insanely cheap one-month trial just yet. You can lock in up to
three years of Xbox Game Pass Ultimate with that same dollar if you play
your cards right.
When you activate Microsoft��s E3 2019 promotion, it not only begins the trial,
but also converts existing Xbox Live Gold and standard Xbox Game Pass
subscriptions on your account to Game Pass Ultimate (normally $15 per
month). Any prepaid time up to the maximum of three years gets the upgrade.
print(iter(c)) #<str_iterator object at 0x7fa21c6c8ac0> 이런게 나왔다면 for문이나 반복문같은 곳에서 사용할 수 있다는 것
print(list(c)) #['R', 'i', 'g', 'h', 't', ' ', 'n', 'o', 'w', ' ', 'g', 'a', 'm'...]
#with문에서는 사용한 후에 close를 호출하지 않아도 내부적으로 리소스가 닫힌다.

 



# 예제3

# read() : 전체 읽기 , read(10) : 10Byte만큼 읽어 옴
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
c = f.read(20)
print(c)
c = f.read(20) #커서가 내부적으로 동작을 해서 내가 마지막에 어디까지 읽었는지를 내부적으로 기억하고 있다.
print(c)
c = f.read(20)
print(c)
f.seek(0,0) #나는 (0,0)으로 이동하고 다시 읽겠다.
c = f.read(20)
print(c)
Right now gamers can
pay just $1 for acc
ess to hundreds of t
Right now gamers can





# 예제4

# readline : 한 줄 씩 읽기
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
line = f.readline() #끝에 \n 줄바꿈이 온다.
print(line)
line = f.readline()
print(line)
Right now gamers can pay just $1 for access to hundreds of titles across PC
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont
#\n줄바꿈에 print()자동 줄바꿈이 만나서 한 줄이 띄어진다.






# 예제5

# readlines : 전체를 읽은 후 라인 단위 리스트로 저장
with open('./resource/it_news.txt', 'r', encoding='UTF-8') as f:
cts = f.readlines()
print(cts) #['Right now gamers can pay just $1 for access to hundreds of titles across PC \n', 'and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont \n', ...]
print()
for c in cts:
print(c, end='') #end=''로 print의 자동 줄바꿈을 없앴다.
Right now gamers can pay just $1 for access to hundreds of titles across PC
and Xbox via Microsoft Xbox Game Pass Ultimate service?but dont
activate that insanely cheap one-month trial just yet. You can lock in up to
three years of Xbox Game Pass Ultimate with that same dollar if you play
your cards right.
When you activate Microsoft��s E3 2019 promotion, it not only begins the trial,
but also converts existing Xbox Live Gold and standard Xbox Game Pass
subscriptions on your account to Game Pass Ultimate (normally $15 per
month). Any prepaid time up to the maximum of three years gets the upgrade.





# 파일 쓰기(write) 기존에 있는 파일을 연결할 때도 오픈을 썼다면 우리가 쓰고자하는 없는 파일을 가상으로
                         연결을 할 때도 open함수를 쓴다.

 


# 예제1

with open('./resource/contents1.txt', 'w') as f:
f.write('I love python\n')

 

contents1.txt

 

I love python

 

 



# 예제2(추가)

with open('./resource/contents1.txt', 'a') as f:
f.write('I love python2\n')
#w를 쓰면 기존의 내용 I love python이 없어지고 I love python2가 덮어씌어진다.

 

contents1.txt

 

I love python
I love python2




# 예제3

# writelines : 리스트 -> 파일
with open('./resource/contents2.txt', 'w') as f:
list = ['Orange\n', 'Apple\n', 'Banana\n', 'Melon\n']
f.writelines(list)

 

contents2.txt

Orange
Apple
Banana
Melon

 

 

 



# 예제4

with open('./resource/contents3.txt', 'w') as f:
print('Test Text Write!', file=f)
print('Test Text Write!', file=f)
print('Test Text Write!', file=f)
#콘솔에 출력되지 않고 contents3파일로 출력을 해준다.

 

contents3.txt

Test Text Write!
Test Text Write!
Test Text Write!

 

 

 

 

 

'Python > Today I learned' 카테고리의 다른 글

TIL#34 클래스 self  (0) 2021.05.20
TIL#33 CSV 파일 읽기 및쓰기  (0) 2021.05.19
TIL#31 외장함수  (0) 2021.05.19
TIL#30 내장함수  (0) 2021.05.19
TIL#29 예외(exception)  (0) 2021.05.19

 

 

외장함수

 

 

 

 

# 파이썬 외장(External)함수
# 실제 프로그램 개발 중 자주 사용
# 종류 : sys, pickle, os, shutil, glob, temfile, time, random 등

 

 

 

외장 함수 기본 실습

외장 함수 설명
중요한 외장 함수
각 함수 예제 실습
os, sys, time중요

 

 

 



# sys : 실행 관련 제어

import sys
# 예제1
print(sys.argv) #['/Users/hong-gildong/Desktop/강의자료/예제 소스 파일/chapter08_02.py']
#그냥 실행하면 리스트 형식으로 현재 실행되는 파일이 첫 번째로 온다.
#두번째 콤마를 찍고부터는 우리가 실행할 때 전달한 값들을 여기서 받을 수가 있다.
#print(sys.argv)는 파이썬 파일을 외부에서 실행할 때 우리가 어떤 함수에서 인자로 넘기듯이
#프로그램을 실행할 때 어떤 값들을 파이썬한테 전달해서 그 값이 1일 경우에는 1번 모드로 실행
#2일 경우에는 2번 모드로 실행... 이런 식으로 어떤 인수(argument)를 받을 수 있다.
# 예제2(강제 종료)
sys.exit()
# 예제3(파이썬 패키지 위치)
print(sys.path)
#['/Users/hong-gildong/Desktop/강의자료/예제 소스 파일', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python39.zip', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages']

 

 

 

 



# pickle : 객체 파일 읽기,쓰기 /파이썬에서 읽을 수 있는 데이터 타입(객체,클래스,딕셔너리,리스트,튜플 )을 파일로 쓸 수 있다.

import pickle
# 예제4(쓰기)
f = open("test.obj", 'wb')
#첫번째 인자: 내가 쓰고 싶은 파일에 대한 정보를 기재 확장자도 마음대로하면 된다.
#두번째 인자: w(write)b(binary)
obj = {1: 'python', 2: 'study', 3: 'basic'}
pickle.dump(obj, f)
f.close()
# 예제5(읽기)
f = open("test.obj", 'rb') #rb(read binary)
data = pickle.load(f)
print(data, type(data)) #{1: 'python', 2: 'study', 3: 'basic'} <class 'dict'>
f.close()

 

 

 

 

 

 

 

# os : 환경 변수, 디렉토리(파일) 처리 관련, 운영체제 작업 관련
# mkdir(폴더를 만듬), rmdir(폴더가 비어있으면 삭제), rename

import os
# 예제6
print(os.environ)#environ({'ATOM_HOME': '/Users/hong-gildong/.atom', 'NODE_PATH': '/private/var/folders/22/drls2s456113jcj0ml...',...})
#운영체제에 대한 환경정보가 나옴. 딕셔너리 형태.
print(os.environ['USER']) #hong-gildong
# 예제7(현재 경로)
print(os.getcwd()) #/Users/hong-gildong/Desktop/강의자료 #파이썬이 실행되고 있는 폴더의 경로를 표시

 

 

 

 



# time : 시간 관련 처리

import time
# 예제8
print(time.time()) #1621425213.353282
# 예제9(형태 변환)
print(time.localtime(time.time()))#time.struct_time(tm_year=2021, tm_mon=5, tm_mday=19, tm_hour=20, tm_min=53, tm_sec=33, tm_wday=2, tm_yday=139, tm_isdst=0)
#현재 시간을 모두 분해해서 보여준다.
#class형태로 보여주고 있다. 객체로 나타내고 있다는 것.
# 예제10(간단 표현)
print(time.ctime()) #Wed May 19 20:53:33 2021
# 예제11(형식 표현)
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))) #2021-05-19 20:53:33
# string format time(Year month day Hour Minute Second)
# 예제12(시간 간격 발생)
for i in range(5):
print(i)
time.sleep(1) #1초마다 이 for문을 한 번씩 실행한다.
0
1
2
3
4

 

 

 

 




# random : 난수 리턴

import random
# 예제13
print(random.random()) #0.7061171413891826 # 0 ~ 1사이의 실수
# 예제14
print(random.randint(1, 45)) #18 #1 ~ 45 사이의 int값을 랜덤으로 갖고 온다.
print(random.randrange(1, 45)) #30 #1 ~ 44 사이의 int값을 랜덤으로 갖고 온다.
# 예제15(섞기) iterable(리스트,튜플,셋과 같은 자료에서 사용 가능) /str은 안되더라...
d = [1, 2, 3, 4, 5]
random.shuffle(d)
print(d) #[5, 3, 4, 2, 1]
# 예제16(무작위 선택) iterable(리스트,튜플,셋과 같은 자료에서 사용 가능)
c = random.choice(d)
print(c) #3

 

 

 



# webbrowser : 본인 OS 의 웹 브라우저 실행

import webbrowser
# 예제17
webbrowser.open("http://google.com")
# 예제18(새창 실행)
webbrowser.open_new("http://naver.com")

 

 

 

'Python > Today I learned' 카테고리의 다른 글

TIL#33 CSV 파일 읽기 및쓰기  (0) 2021.05.19
TIL#32 파일 읽기 및 쓰기  (0) 2021.05.19
TIL#30 내장함수  (0) 2021.05.19
TIL#29 예외(exception)  (0) 2021.05.19
TIL#28 import error 상대경로 절대경로  (0) 2021.05.18

 

 

 

 

 

 

내장함수

 

 

 

# 파이썬 내장(Built-in) 함수
# 자주 사용하는 함수 위주로 실습
# 사용하다보면 자연스럽게 숙달
# str(), int(), tuple() 형변환 이미 학습

 

 


내장 함수 기본 실습

내장 함수 종류
중요한 내장 함수
각 함수 예제 실습
filter,map,zip


 

 

 


# 절대값
# abs()

print(abs(-3)) #3

 

 

 

 


# all, any : iterable 요소 검사(참, 거짓)

print(all([1,2,3])) #True / and 안의 요소들이 모두 true일 때 true가 나옴.
print(any([1,2,0])) #True / or 안의 요소 중에 하나라도 true면 true가 나온다.

 

 

 



# chr : 아스키 -> 문자 , ord : 문자 -> 아스키

print(chr(67)) #C
print(ord('C')) #67

 

 

 

 



# enumerate : 인덱스 + Iterable 객체 생성

for i, name in enumerate(['abc', 'bcd', 'efg']):
print(i, name)
0 abc
1 bcd
2 efg

 

 

 




#  filter : 반복가능한 객체 요소(ex>리스트)를 지정한 함수 조건에 맞는 값 추출

def conv_pos(x):
return abs(x) > 2
print(list(filter(conv_pos, [1, -3, 2, 0, -5, 6]))) #[-3, -5, 6] 리스트로 형변환을 해줘야한다.
print(list(filter(lambda x: abs(x) > 2, [1, -3, 2, 0, -5, 6]))) #[-3, -5, 6] 람다식

 

 

 

 

 



# id : 객체의 주소값(레퍼런스) 반환

print(id(int(5))) #2801488849328
print(id(4)) #2801488849296

 

 

 

 

 


# len : 요소의 길이 반환 /인자로 넣은 iterable한 반복 가능한 객체의 길이를 반환한다고 이해하면 된다.

print(len('abcdefg')) #7
print(len([1,2,3,4,5,6,7])) #7

 

 

 

 

 



# max, min : 최대값, 최소값

print(max([1,2,3])) #3
print(max('python study')) #y
print(min([1,2,3])) #1
print(min('python study')) # 최소값이 공백으로 나온다.

 

 

 

 

 



# map : 반복가능한 객체 요소를 지정한 함수 실행 후 추출

def conv_abs(x):
return abs(x)
print(list(map(conv_abs,[1,-3,2,0,-5,6]))) #[1, 3, 2, 0, 5, 6]
print(list(map(lambda x:abs(x),[1,-3,2,0,-5,6]))) #[1, 3, 2, 0, 5, 6]

 

 

 

 

 

 



# pow : 제곱값 반환

print(pow(2,10)) #1024

 

 

 

 

 


# range : 반복가능한 객체(Iterable) 반환

print(range(1,10,2)) #range(1, 10, 2)
print(list(range(1,10,2))) #[1, 3, 5, 7, 9]
print(list(range(0,-15,-1))) #[0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14]

 

 

 



# round : 반올림

print(round(6.5781, 2)) #6.58
print(round(5.6)) #6 두번째 인자를 놓지 않을 경우 첫째자리에서 반올림한다.

 

 

 

 



# sorted : 반복가능한 객체(Iterable) <list dictionary tuple set> 정렬 후 반환

print(sorted([6,7,4,3,1,2])) #[1, 2, 3, 4, 6, 7]
a = sorted([6,7,4,3,1,2])
print(a) #[1, 2, 3, 4, 6, 7]
print(sorted(['p','y','t','h','o','n'])) #['h', 'n', 'o', 'p', 't', 'y']

 

 

 

 




# sum : 반복가능한 객체(Iterable) 합 반환

print(sum([6,7,8,9,10])) #40
print(sum(range(1,101))) #5050

 

 

 

 



# type : 자료형 확인

print(type(3)) #<class 'int'>
print(type({})) #<class 'dict'>
print(type(())) #<class 'tuple'>
print(type([])) #<class 'list'>

 

 

 

 

 



# zip : 반복가능한 객체(Iterable)의 요소를 묶어서 반환

print(list(zip([10,20,30],[40,50,777]))) #[(10, 40), (20, 50), (30, 777)]
#하나의 list안에 세 개의 tuple이 들어있는 걸로 묶어서 반환했다.
print(list(zip([10,20,30],[40,50,]))) #[(10, 40), (20, 50)] 짝이 안맞으면 맞는 것만 반환한다.
print(type(list(zip([10,20,30],[40,50,777]))[0])) #<class 'tuple'>

 

 

 

 

 

'Python > Today I learned' 카테고리의 다른 글

TIL#32 파일 읽기 및 쓰기  (0) 2021.05.19
TIL#31 외장함수  (0) 2021.05.19
TIL#29 예외(exception)  (0) 2021.05.19
TIL#28 import error 상대경로 절대경로  (0) 2021.05.18
TIL#27 패키지와 import  (0) 2021.05.18

 

 

 

 

 

예외(Exception)

 

 

 

# 파이썬 예외처리의 이해


##예외는 우리가 작성한 코드에서 비정상적으로 발생하는 이벤트
##에러는 예외와 다르게 운영환경에서 발생 ex)정전,하드웨어적인 고장
##예외를 에러의 범주에 포함하기도 한다. 그러니 나눠서 외우지 말자.

 

 

 


예외(Exception)개념 및 처리

예외 종류
다양한 예외 재연
예외 처리 기본
예외 처리 패턴
예외 처리 실습

 

 



# 예외 종류
SyntaxError, TypeError, NameError, IndexError, ValueError, KeyError....
# 문법적으로는 예외가 없지만, 코드 실행 프로세스(단계)발생하는 예외도 중요
#(나는 이렇게 만들었는데 사용자가 전혀 다른 값으로 입력했을 때)


# 1. 예외는 반드시 처리
# 2. 로그는 반드시 남긴다.(어떤 예외가 발생했었는지를 기록으로 남기는 것)
# 3. 예외는 던져진다.(다른 데로 처리를 위임할 수 있다.)
# 4. 예외 무시(권장 x)

 

 

 


# SyntaxError : 문법 오류

print('error) #SyntaxError: EOL while scanning string literal
print('error')) #SyntaxError: unmatched ')'
if True #SyntaxError: invalid syntax
pass

 

 



# NameError : 참조 없음(없는 변수를 참조할 때)

a = 10
b = 15
print(c) #NameError: name 'c' is not defined

 

 

 

 


# ZeroDivisionError

print(100 / 0) #ZeroDivisionError: division by zero
#100을 0으로 나누는 것

 

 



# IndexError

x = [50, 70, 90]
print(x[1])
print(x[4]) #IndexError: list index out of range
print(x.pop())
print(x.pop())
print(x.pop())
print(x.pop()) #IndexError: pop from empty list

 

 

 



# KeyError

dic = {'name': 'Lee', 'Age': 41, 'City': 'Busan'}
print(dic['hobby']) #KeyError: 'hobby'
print(dic.get('hobby')) #None get메소드는 예외를 발생시키지 않고 없으면 None을 가져온다.



# 예외 없는 것을 가정하고 프로그램 작성 -> 런타임(실행할 때) 예외 발생 시 예외 처리 권장(EAFP)

 

 

 

 


# AttributeError : 모듈, 클래스에 있는 잘못된 속성 사용 예외

import time
print(time.time2()) #AttributeError: module 'time' has no attribute 'time2'
#time모듈에서는 time2라는 메소드가 없기 때문에 attributeerror가 나온다.

 

 

 




# ValueError 어떤 자료구조 안에서, 어떤 데이터를 참조하려고 하는데 그때 존재하지 않을 때

x = [10, 50, 90]
x.remove(50)
print(x) #[10, 90]
x.remove(200) #ValueError: list.remove(x): x not in list

 

 



# FileNotFoundError

f = open('test.txt') #FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'
# test.txt.파일이 없기 때문에

 

 

 



# TypeError : 자료형에 맞지 않는 연산을 수행 할 경우 ex)숫자+문자

x = [1,2]
y = (1,2)
z = 'test'
print(x + y) #TypeError: can only concatenate list (not "tuple") to list
print(x + z) #TypeError: can only concatenate list (not "str") to list
print(y + z) #TypeError: can only concatenate tuple (not "str") to tuple
print(x + list(y)) #[1, 2, 1, 2]
print(x + list(z)) #[1, 2, 't', 'e', 's', 't']

 

 

 

 


# 예외 처리 기본
# try : 에러가 발생 할 가능성이 있는 코드 실행
# except 에러명1: 여러개 가능
# except 에러명2:
# else : try 블록의 에러가 없을 경우 실행
# finally : 항상 마지막에 실행

 

 

 

name = ['Kim', 'Lee', 'Park']

 


# 예제1

try:
z = 'Kim' # 'Cho'를 적으면 else문이 실행되지 않는다.
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except ValueError:
print('Not found it! - Occurred ValueError!')
else:
print('Ok! else.')
#Kim Found it! 1 in name
#Ok! else.
#Not found it! - Occurred ValueError! <- z = 'Cho'를 적었을 때





# 예제2

try:
z = 'Cho' # 'Cho'
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except: #except Exception으로 적어도 됨 이렇게 하면 모든 에러를 다잡지만 정확히 어떤 에러인지는 모른다.
print('Not found it! - Occurred ValueError!')
else:
print('Ok! else.')
#Not found it! - Occurred ValueError!

 




# 예제3

try:
z = 'Cho' # 'Cho'
x = name.index(z)
print('{} Found it! {} in name'.format(z, x + 1))
except Exception as e: #alias를 주고 출력을 할 수도 있다.
print(e)
print('Not found it! - Occurred ValueError!')
else:
print('Ok! else.')
finally:
print('Ok! finally') #예외가 발생해도 실행됨. 무조건 한 번 실행한다.
#'Cho' is not in list <- print(e)
#Not found it! - Occurred ValueError!
#Ok! finally





# 예제4
# 예외 발생 : raise
# raise 키워드로 예외 직접 발생

try:
a = 'Park'
if a == 'Park':
print('OK! Pass!')
else:
raise ValueError #직접 valueError를 발생시키는 것
except ValueError:
print('Occurred! Exception!')
else:
print('Ok! else!')
#OK! Pass!
#Ok! else!
#Occurred! Exception! <- a = 'kim'일 경우

 

 

 

 

'Python > Today I learned' 카테고리의 다른 글

TIL#31 외장함수  (0) 2021.05.19
TIL#30 내장함수  (0) 2021.05.19
TIL#28 import error 상대경로 절대경로  (0) 2021.05.18
TIL#27 패키지와 import  (0) 2021.05.18
TIL#26 모듈과 import, sys.path  (0) 2021.05.18

+ Recent posts