Python/numpy & Pytorch

csv 파일 json으로 바꾸기

파송송 2024. 3. 29. 01:39
728x90

csv 파일을 json으로 바꿔야 하는 상황이 생겨서 변경하고자 한다.

 

import csv
import json
import pandas as pd


csv_file_path = '파일 경로'
data =  df_tweet = pd.read_csv(csv_file_path)
data

with open(csv_file_path, 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    next(reader)  # 첫 줄 skip

    # 각 라인마다 딕셔너리 생성 후 리스트에 추가
    data = []
    for line in reader:
        d = {
            'Topic': line[0],
            'Sentiment': line[1],
            'TweetId': int(line[2]),
            'TweetDate': line[3],
            'TweetText': line[4]
        }
        data.append(d)
json_string = json.dumps(data, ensure_ascii=False, indent=4)

txt_file_path = 'data.json'

# txt 파일 쓰기
with open(txt_file_path, 'w', encoding='utf-8') as f:
    f.write(json_string)

indent는 col 개수로 설정해 준다.

 

json으로 변한 걸 확인할 수 있다! 

728x90