[TIL #33] 외부 파일 다루기

안떽왕·2023년 5월 3일
0

Today I Learned

목록 보기
34/76

파일 입출력

  • r : 읽기 모드
  • w : 쓰기 모드
  • a : 추가

open() : 파일열기

read(): 파일 전체 내용 읽기

readline(): 파일 한 줄씩 읽기

JSON 다루기

json.load: JSON파일을 Python 객체(딕셔너리)로 변환

import json

# JSON 문자열
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# JSON 문자열을 Python 객체로 변환
data = json.loads(json_data)

# Python 객체 출력
print(data)
print(type(data))

json.dump: 파이썬 객체를 json파일로 변환

import json

# Python 객체
data = {'name': 'John', 'age': 30, 'city': 'New York'}

# Python 객체를 JSON 파일로 변환
with open('dump.json', 'w') as file:
    json.dump(data, file)

실행하게 되면 밑과 같이 작성된 dump.json이라는 파일이 생성됩니다.

{"name": "John", "age": 30, "city": "New York"}

requests 모듈 다루기

get 요청 보내기

pip install requests를 하고 import를 해주어야 합니다.

해당 주소는 테스트하기 위한 연습 코드들이 담긴 사이트입니다.

파일 실행 시 해당 페이지에 담긴 데이터들이 출력 됩니다.

import requests

response = requests.get('https://jsonplaceholder.typicode.com/posts')
print(response.text)

post요청 보내기

data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.post(
    'https://jsonplaceholder.typicode.com/posts', data=data)
print(response.text)

put, delete 요청 보내기

import requests

data = {'title': 'foo', 'body': 'bar', 'userId': 1}
response = requests.put(
    'https://jsonplaceholder.typicode.com/posts/1', data=data)
print(response.text)

response = requests.delete('https://jsonplaceholder.typicode.com/posts/1')
print(response.text)

curl

요청을 확인하는 방법으로 postman을 쓰고 있지만 더 빠른 개발을 추구할 때에는 curl가 좋은 선택지일 것 같습니다. 사용 예시는 아래와 같습니다.

curl -X POST -d "title=foo&body=bar&userId=1" https://jsonplaceholder.typicode.com/posts

curl -X PUT -d "title=foo&body=bar&userId=1" https://jsonplaceholder.typicode.com/posts/1

curl -X DELETE https://jsonplaceholder.typicode.com/posts/1

profile
이제 막 개발 배우는 코린이

0개의 댓글