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() # 파일 닫아줘야 함
import json
json_1 = open('_____.json', encoding = 'utf-8')
json_1_dict = json.load(json_1) # dict or list 변환
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/