python

python 파일

개발롬 2023. 3. 11. 21:45

파일 읽기와 쓰기

  • open 메소드 활용하기

1) read() : 파일의 내용을 문자열로 반환

file_path = 'soohyun.txt'
open_file = open(file_path, 'r')
text = open_file.read()
open_file.close()

2) readlines() : 파일의 내용을 개행 문자 기준으로 나눠 문자열 리스트를 반환

file_path = 'soohyun.txt'
open_file = open(file_path, 'r')
text = open_file.readlines()
open_file.close()

3) with : close 를 하지 않아도 됩니다. 들여쓰기가 끝나는 위치에서 파일을 닫ㄷ고 리소스를 자동으로 해제합니다.

file_path = 'soohyun.txt'
open_file = open(file_path, 'r')
with open(file_path, 'r') as open_file:
    text = open_file.read_lines()

4) json.dump : python dictionary를 json 파일로 생성

import json

with open('new_file.json', 'w') as opened_file:
    a = json.dump(dict_data, opened_file)

5) csv 모듈로 CSV 파일 읽기

import csv

file_path = '/Users/soohyunlee/Desktop/test.csv'

with open(file_path, newline='') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for _ in range(3):
        print(next(reader))

>>
['id', 'created_at', 'updated_at', 'name', 'image_url', 'gender', 'age']
['1', '2023-03-10 16:04:04.326632', '2023-03-11 10:02:27.879025', 'soo', 'https://image.test.com/image_1.jpg', 'F', '20']
['2', '2023-03-10 16:04:04.330564', '2023-03-10 16:04:04.332764', 'soo', 'https://image.test.com/image_1.jpg', 'F', '22']

6. 여러개의 파일을 한 라인씩 파싱하기

wilth open('text1.txt', 'r') as file1:
    with open('text2,txt', 'w') as file2:
        for line in file1:
            file2.write(line)

텍스트 암호화

1) hashlib 으로 해싱하기

  • SHA1, SHA224, SHA384 등 보안 알고리즘이 포함
import hashlib

secret = 'secret key ABCDEFG'  
encode_secret = secret.encode()  
m = hashlib.md5()  
m.update(encode_secret)  
data = m.digest()

print(data)
> > b'Z\\x8f\\x19{\\x06Rn\\x8a\\xcb\\xf1+\\xeb\\x08\\xffL\\xb0'

2) cryptography 로 암호화

  • 암호화를 처리하기 위해 python 에서 주로 사용되는 라이브러리
  • 대칭키 암호화 : 양측이 둘다 키를 공유하고 있어야합니다.
from cryptography.fernet import Fernet

key = Fernet.generate_key()  
print(key)

> > b'jQWLbRd-UIHUqJqdG\_B7idUdu1uMFSda8JBWijKS17E='  
> > 이 키는 안전하게 보관하기!!
  • 데이터 암호화 하기
f = Fernet(key)  
message = b'This is secret'  
encrypted = f.encrypt(message)

print(encrypted)
>> b'gAAAAABkDG8ZTQGXRkGcD8V6nEJmHl7vR-WqMsBxBfqa2FqLpNwnTtUm1oBYlOAKLD70e0t9Wfov8oUZH3UHhzw0MWuYNXjmhA=='
  • 데이터 복호화 하기
f = Fernet(key)
data = f.decrypt(encrypted)

print(data)
>> b'This is secret'