본문 바로가기

연구일지

[오늘의 팁들] file append writing/json encoding/int list to str list

728x90
반응형

1. append writing

원래 file writing을 하게 되면,

with open('t.txt', 'w', encoding='utf-8) as f:
    f.write('hello!\n')

이런 식으로 원래 있던 값이 없어지고 새로운 값이 덧쓰이게 된다.

 

파일에 있던 원래 값을 유지하고 싶다면, 옵션 'a'를 이용하면 된다.

with open('t.txt', 'a', encoding='utf-8) as f:
    f.write('hello!\n')

이런 식으로 바꿔주면, 계속 덧붙여서 쓸 수 있다.

 

2. ensure_ascii

 

json파일을 읽고 쓸 때, 가끔이라쓰고 대부분 encoding='utf-8'을 지정해도 한글이 깨지는 경우가 발생한다.

 

그럴때는 json.dump를 할 때, ensure_ascii=False로 옵션을 지정해주면 된다.

 

with open('file_path.json', 'w', encoding='utf-8') as f:
	json.dump(data, f, indent=4, ensure_ascii=False)

+ indent도 지정해서 가독성을 높여주면 더 좋다.

 

3. int list to str list

 

join 등을 사용하고 싶을 때, integer형식 값이 있는 list는 한정적이다. 이런 경우 string형식 값이 있는 list로 바꿔주는 게 좋은데, for 문을 도는 것도 방법이겠지만 이 방법이 더 간단할 수 있다.

 

list_int = [1, 12, 15, 21, 131] 
list_string = list(map(str, list_int))

이런 식으로 바꿔주면, ['1', '12', '15', '21', '131']로 나오게 된다.

728x90
반응형