Python - 파일 다루기

lsjoon·2023년 2월 24일
0

python

목록 보기
8/16

파일 열기 (open, read)

<Script>

// 동일 코드
=> file = open('data.txt')
content = file.read()
file.close()

=> with open('data.txt') as file:
	content = file.read()
    
    
---
// 줄 단위로 읽기
contents = []
with open('data.txt') as file:
	for line in file:
    	content.append(line)
        
---
//쓰기 모드로 열기
with open('data.txt', 'w') as file:
	file.write('Hello')

</Script>

데이터 관리

<Script>

list.strip()
=> 각 줄의 앞-뒤의 모든 공백이 사라짐(공백 문자)

dict_list = {}
with open (filename) as file:
  for line in file:
  // ':'를 기준으로 문자열을 나누어 각각 'user'와 'title'에 저장
      user, title = line.strip().split(':')
  // 변수 dict_list 에 'dictionary'의 key(user):value(title) 형태로 저장
      dict_list[user] = title
	
    return dict_list
    
</Script>

JSON

<Script>

import json

// loads = JSON 형태의 문자열을 dictionary 로 변환, 모든 원소는 str 타입
with open(filename) as file:
	json_string = file.read()
	return json.loads(json.string)

// dumps = dictionary 를 JSON 형태의 문자열로 변환
with open(filename, 'w') as file:
	json_string = json.dumps(dictionary)
    file.write(json_string)

</Script>

0개의 댓글