ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL 2023.05.03
    내일배움캠프 2023. 5. 3. 20:44

    파일 입출력

    “r” - 읽기모드 - 파일을 읽기만 할 때 사용

    “w” - 쓰기모드 - 파일에 내용을 쓸 때 사용

    “a” - 추가모드 - 파일의 마지막에 새로운 내용을 추가 시킬 때 사용

    “x”

    “b”

    “t”

     

    파일열기:

    open(경로 + 모드)

    파일을 열었으면 닫아줘야함

     

    파일 읽기:

    read()

    readline()

    readlines()

     

    파일쓰기:

    write()

    # 파일을 쓰기 모드로 엽니다.
    file = open("example.txt", "w")
    
    # 파일에 데이터를 작성합니다.
    file.write("Hello, world!\n")
    file.write("This is an example file.\n")
    file.write("Writing some lines.\n")
    
    # 파일을 닫습니다.
    file.close()
    
    # 파일을 읽기 모드로 열고 데이터를 읽는 예제입니다.
    file = open("example.txt", "r")
    
    # 파일 전체를 읽어옵니다.
    contents = file.read()
    print("전체 내용:")
    print(contents)
    
    # 파일을 닫습니다.
    file.close()
    
    # 파일을 다시 읽기 모드로 열고 한 줄씩 읽는 예제입니다.
    file = open("example.txt", "r")
    
    print("한 줄씩 읽기:")
    # 파일의 각 줄을 반복하며 읽어옵니다.
    for line in file:
        print(line.strip())
    
    # 파일을 닫습니다.
    file.close()
    
    # 파일을 읽기 모드로 열고 모든 줄을 읽어 리스트로 반환하는 예제입니다.
    file = open("example.txt", "r")
    
    lines = file.readlines()
    print("리스트로 읽기:")
    print(lines)
    
    # 파일을 닫습니다.
    file.close()

     

     

    Json 

    Json 다루기 -JSON 파싱

    json.loads: JSON 문자열을 파이썬 객체(딕셔너리)로 변환

    json.load: JSON 파일을 파이썬 객체로 변환

     

    Json 다루기 -JSON 직렬화

    json.dumps: 파이썬 객체를 JSON 문자열로 변환

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

     

    동기화

    파일을 먼저 쓰고 작업이 돼야 함

    파일이 써지지 않았는데 작업이 될 수 없음

    await 이용

    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 파일 읽기
    with open('data.json') as file:
        data = json.load(file)
    
    print(data['employee'])
    print(data['employee']['name'])
    print(data['employee']['salary'])
    
    # Python 객체
    data = {'name': 'John', 'age': 30, 'city': 'New York'}
    
    # Python 객체를 JSON 파일로 변환
    with open('data2.json', 'w') as file:
        json.dump(data, file)

     

     

    Request 모듈 다루기

    일단은 리퀘스트 모듈을 사용 하려면 리퀘스트가 설치가 돼있어야함

    pip install requests

     

    status 코드도 확인 가능

    import requests
    
    response = requests.get('https://jsonplaceholder.typicode.com/posts')
    print(response.text)
    
    data = {'title': 'foo', 'body': 'bar', 'userId': 1}
    response = requests.post('https://jsonplaceholder.typicode.com/posts', data=data)
    print(response.text)
    print(response.status_code)
    
    
    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 이라는 명령어가 있다

     

    CURL

    기본적으로 아마 설치 돼 있음

    사용법은 단순

     

    curl https://jsonplaceholder.typicode.com/posts

    curl -X GET https://jsonplaceholder.typicode.com/posts

     

    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

     

     

    CSV 다루기

    json보다 많이 사용되진 않음

    ai나  기상 데이터 등 대용랑 데이터를 구분하기 위해선 csv로 표시하긴 하는데

    백엔드는 보통 json

     

    csv 읽기

    csv.reader 리스트 형태 순회가 가능함

    csv.DictReader 딕셔너리 형태로 읽음

     

    쓰기

    csv.writer 로 가져와서

    .writerow 쓰기

    # 파이썬에서 csv 파일을 다루기 위해 모듈 import
    import csv
    
    csv_path = "sample2.csv"
    
    # csv 파일을 쓸 때는 newline='' 옵션을 줘서 중간에 공백 라인이 생기는 것을 방지합니다.
    csv_file = open(csv_path, "a", encoding="utf-8", newline='')
    
    #  파일 객체를 인수로 받아들이고 writer 객체를 반환
    #  writer 객체의 writerow() 메서드를 사용하여 각 행을 쓸 수 있다
    csv_writer = csv.writer(csv_file)
    
    # csv에 데이터를 추가합니다.
    csv_writer.writerow(["lee@sparta.com", '1989', "lee", "Seoul"])
    
    csv_file.close()
    
    csv_file = open(csv_path, "r", encoding="utf-8")
    csv_data = csv.reader(csv_file)
    for i in csv_data:
        print(i)
    
    csv_file.close()
    
    # result output
    """
    ...
    ['lee@sparta.com', '1989', 'lee', 'Seoul'] # 추가 된 행
    """

    '내일배움캠프' 카테고리의 다른 글

    TIL 2023.05.05  (0) 2023.05.05
    TIL 2023.05.04  (0) 2023.05.04
    TIL 2023.05.02  (2) 2023.05.02
    TIL 2023.05.01  (0) 2023.05.01
    WIL 내일배움캠프 7주차  (0) 2023.04.28
Designed by Tistory.