CSV(Comma Separated Values)는 아래와 같이 comma로 구분되어 저장된 데이터 형식을 말합니다.
SN, Country, City
1, Korea, Seoul
2, Japanese, Tokyo
파이썬에서 CSV 파일을 읽고 쓰는 방법에 대해서 알아보겠습니다.
1. CSV 파일 읽기
다음과 같이 데이터가 comma로 구분된 CSV 파일이 있습니다.
SN,Country,City
1,Korea,Seoul
2,Japanese,Tokyo
아래와 같이 csv 모듈을 사용하여 comma로 구분된 CSV 파일을 읽을 수 있습니다.
import csv
with open("countries.csv", 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Output:
['SN', 'Country', 'City']
['1', 'Korea', 'Seoul']
['2', 'Japanese', 'Tokyo']
2. 다른 구분자를 사용하는 CSV 파일 읽기
아래와 같이 ,
대신에 스페이스나 Tab과 같은 구분자를 사용하는 CSV 파일이 있을 수 있습니다.
SN Country City
1 Korea Seoul
2 Japanese Tokyo
csv 모듈은 csv.reader(file, delimiter)
과 같이 구분자를 인자로 받아, 다른 구분자로 만들어진 CSV 파일을 읽을 수 있습니다.
아래 예제에서는 delimiter=' '
로 스페이스를 구분자로 전달하여 위의 CSV 파일을 읽습니다.
import csv
with open("countries2.csv", 'r') as file:
reader = csv.reader(file, delimiter=' ')
for row in reader:
print(row)
Output:
['SN', 'Country', 'City']
['1', 'Korea', 'Seoul']
['2', 'Japanese', 'Tokyo']
3. CSV 파일을 dict로 읽기
리스트가 아닌 key-value
형태의 딕셔너리로 CSV 파일을 읽으려면 아래와 같이 DictReader()
를 사용하면 됩니다.
import csv
with open("countries.csv", 'r') as file:
reader = csv.DictReader(file)
for row in reader:
print(dict(row))
Output:
{'SN': '1', ' Country': ' Korea', ' City': ' Seoul'}
{'SN': '2', ' Country': ' Japanese', ' City': ' Tokyo'}
4. CSV 형식으로 파일 쓰기 (1)
다음은 CSV 형식으로 파일을 저장하는 예제입니다. header, row 순서로 쓰면 됩니다.
import csv
with open("cities.csv", 'w') as file:
writer = csv.writer(file)
writer.writerow(["SN", "City", "Country"])
writer.writerow(["1", "Seoul", "Korea"])
writer.writerow(["1", "Tokyo", "Japanese"])
cities.csv
파일을 열어보면 아래와 같이 저장됩니다.
SN,City,Country
1,Seoul,Korea
1,Tokyo,Japanese
5. CSV 형식으로 파일 쓰기 (2)
아래와 같이 모든 데이터가 있는 리스트를 writerows()
에 인자로 전달하여 한번에 쓸 수 있습니다.
import csv
csv_rows = [["SN", "City", "Country"], ["1", "Seoul", "Korea"], ["1", "Tokyo", "Japanese"]]
with open("cities.csv", 'w') as file:
writer = csv.writer(file)
writer.writerows(csv_rows)
cities.csv
파일을 열어보면 아래와 같이 저장됩니다.
SN,City,Country
1,Seoul,Korea
1,Tokyo,Japanese
6. 구분자 변경하여 CSV 형식으로 파일 쓰기
comma가 아닌 다른 구분자로 CSV 파일을 만들 수 있습니다. 아래와 같이 writer(file, delimiter)
함수에 원하는 구분자를 인자로 전달하면 됩니다.
import csv
with open("cities.csv", 'w') as file:
writer = csv.writer(file, delimiter=' ')
writer.writerow(["SN", "City", "Country"])
writer.writerow(["1", "Seoul", "Korea"])
writer.writerow(["1", "Tokyo", "Japanese"])
cities.csv
파일을 열어보면 아래와 같이 저장됩니다.
SN City Country
1 Seoul Korea
1 Tokyo Japanese
7. dict로 CSV 파일 쓰기
아래와 같이 key-value
형태의 딕셔너리 객체로 CSV 파일을 만들 수 있습니다.
import csv
with open("cities.csv", 'w') as file:
header = ["SN", "City", "Country"]
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
writer.writerow({"SN": "1", "City": "Seoul", "Country": "Korea"})
writer.writerow({"SN": "2", "City": "Tokyo", "Country": "Japanese"})
cities.csv
파일을 열어보면 아래와 같이 저장됩니다.
SN,City,Country
1,Seoul,Korea
2,Tokyo,Japanese
Related Posts
- Python 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기