[Python]load file(txt, json)

Jae Gyeong Lee·2022년 12월 5일

1. txt

r = 읽기모드
w = 쓰기모드
a = 추가모드(파일 마지막에 새 내용을 추가할 때 사용)

readline: 첫 번째 줄을 읽어옴, 모든 줄을 다 읽으려면 반복문(while 또는 for) 사용.
readlines: 모든 줄을 읽어옴, list 형태로 return.
read: 모든 줄을 읽어옴, str 형태로 return.

with open("foo.txt", "w", encoding = '인코딩 방식') as f:
    f.write("Life is too short, you need python") #쓰기
with open("foo.txt", "r", encoding = '인코딩 방식') as f:
    f.readlines() #읽기
f.writelines(['1line', '2line', '3line'])
  • writelines()
    - 여러 줄의 텍스트를 한 번에 입력하는 함수
    - 리스트 자료형, 튜플 자료형 안에 문자열로 구성

  • f.name
    - 파일 오픈 시 사용한 파일의 경로를 알려줌

참고) 결과를 화면에 출력하지 말고 지정된 위치의 파일로 바로 저장해라

orig_stdout = sys.stdout # 결과 출력 위치 변경, 표준 출력 방향을 바꿔준 것

f = open(f_name , 'a' , encoding='UTF-8')
sys.stdout = f


위의 코드(sys.stdout)를 작성하면, 아래의 print 문이 출력되지 않고 바로 파일에 저장됨.

for i in content_list:
    print(i.text.strip())
    print("\n")

sys.stdout = orig_stdout # 결과 출력 위치 원상 복구(작업이 끝났으니 원래의 상태로 되돌림)

f.close() # 파일 닫아줘야 함

2. json

import json

방법1

json_1 = open('_____.json', encoding = 'utf-8')
json_1_dict = json.load(json_1) # dict or list 변환

방법2

with open('_____.json', 'r', encoding = 'utf-8') as f:
    json_file = json.load(f)
#보기 쉽게 출력1
print(json.dumps(json_file, indent=3)) # indent parameter: 들여쓰기 탭 수
#보기 쉽게 출력2
from pprint import pprint
pprint(json_file)

https://devpouch.tistory.com/33
https://codechacha.com/ko/python-read-write-json-file/

profile
안녕하세요 반갑습니다. 공부한 내용들을 기록하고 있습니다.

0개의 댓글