최  호민

최 호민

1677687060

Python에서 CSV 파일을 만드는 2가지 방법

csv라는 Python 내장 모듈을 사용하여 CSV 파일을 만드는 방법을 알아봅니다. Python에서 CSV 파일을 만드는 두 가지 방법: csv.DictWriter 클래스 및 csv.writer 클래스 사용

Python에서 CSV 파일을 만드는 방법은 무엇입니까? 

CSV는 쉼표로 구분된 값의 약어입니다. 스프레드시트와 같이 테이블 형식 데이터를 저장하는 데 사용할 수 있는 파일 형식입니다. 테이블 형식 데이터베이스의 데이터를 저장하는 데 사용할 수도 있습니다.

CSV 파일의 각 행을 데이터 레코드로 참조할 수 있습니다. 각 데이터 레코드는 쉼표로 구분된 하나 이상의 필드로 구성됩니다.

이 문서에서는 csv 라는 Python 내장 모듈을 사용하여 CSV 파일을 만드는 방법을 보여줍니다. 이 자습서를 완전히 이해하려면 Python 프로그래밍 언어의 기초를 잘 이해하고 있어야 합니다.

csv 모듈에는 데이터를 CSV에 쓰는 데 사용할 수 있는 두 가지 클래스가 있습니다. 이러한 클래스는 다음과 같습니다.

  • 수업 csv.writer_
  • 수업 csv.DictWriter_

클래스를 사용하여 CSV 파일을 만드는 방법csv.writer

csv.writer 클래스를 사용하여 데이터를 CSV 파일에 쓸 수 있습니다 . 이 클래스는 데이터를 구분된 문자열로 변환하는 데 사용할 수 있는 기록기 개체를 반환합니다.

인용된 필드 내의 줄 바꿈 문자가 올바르게 해석되도록 하려면 newline='' 을 사용하여 CSV 파일 개체를 엽니다 .

csv.writer 클래스 의 구문은 다음과 같습니다.

csv.writer(csvfile, dialect=’excel’, **fmtparams)

이제 구문에 사용된 다양한 매개변수의 의미를 안내해 드리겠습니다.

  1. 매개 변수 는 메서드 csvfile 가 있는 csvfile 개체를 나타냅니다 write().
  2. 선택적 dialect매개변수는 CSV 파일 작성에 사용할 수 있는 방언의 이름을 나타냅니다.
  3. 선택적 매개변수는 언어에 지정된 매개변수를 덮어쓰는 데 사용할 수 있는 형식 매개변수를 fmtparams나타냅니다 .

csv.writer 클래스에는 데이터를 CSV 파일 쓰는 데 사용할 수 있는 두 가지 메서드가 있습니다. 방법은 다음과 같습니다.

방법 writerow()_

writerow()메서드는 반복 가능한 데이터를 매개변수로 받은 다음 데이터를 단일 행의 CSV 파일에 씁니다. writerow() 메서드 의 인기 있는 사용법 중 하나 는 CSV 파일의 필드 행을 작성하는 데 사용하는 것입니다.

이제 writerow() 메서드를 사용하여 CSV 파일에 단일 행을 쓰는 방법을 보여드리겠습니다 .

코드 편집기에서 이름이 profiles1.py 인 파일을 만듭니다 . 그런 다음 파일에 다음 코드를 작성합니다.

import csv

with open('profiles1.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    field = ["name", "age", "country"]
    
    writer.writerow(field)
    writer.writerow(["Oladele Damilola", "40", "Nigeria"])
    writer.writerow(["Alina Hricko", "23", "Ukraine"])
    writer.writerow(["Isabel Walter", "50", "United Kingdom"])

코드 입력에 대한 설명은 profiles1.py다음과 같습니다.

  1. 첫 번째 줄은 Python csv 모듈을 가져옵니다.
  2. 두 번째 줄은 가져온 모듈을 나머지 코드와 구분하는 빈 줄입니다.
  3. 코드의 세 번째 줄은 함수의 도움으로 CSV 파일을 쓰기(w 모드)로 엽니다 open().
  4. 네 번째 줄은 writer() 함수를 호출하여 CSV 작성기 개체를 만들고 변수에 저장합니다 writer.
  5. fields다섯 번째 줄 은 CSV 파일의 열 제목을 각각 나타내는 문자열로 구성된 목록을 저장하는 이라는 변수를 만듭니다 .
  6. 6행 이하는 CSV Writer 객체의 writerow() 메소드를 호출하여 필드 데이터 및 기타 데이터를 CSV 파일에 씁니다.

완료되면 명령줄 터미널로 이동하여 Python 파일 profiles1.py 가 있는 디렉터리로 이동합니다 . 다음 명령을 실행합니다.

python profiles1.py

다음 텍스트가 포함된 작업 디렉토리에 profiles1.csv 라는 이름의 CSV 파일이 있어야 합니다 .

name,age,country
Oladele Damilola,40,Nigeria
Alina Hricko,23,Ukraine
Isabel Walter,50,United Kingdom

방법 writerows()_

writerows () 메서드는 writerow() 메서드와 사용법이 유사합니다. 유일한 차이점은 writerow() 메서드는 단일 행을 CSV 파일에 쓰는 반면 writerows () 메서드를 사용하면 CSV 파일에 여러 행을 쓸 수 있다는 것입니다.

writerows() 메서드의 작동 방식을 보려면 작업 디렉터리에 profiles2.py 라는 파일을 만듭니다 . 그런 다음 생성한 파일에 다음 코드를 작성합니다.

import csv

with open('profiles2.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    row_list = [
        ["name", "age", "country"], 
        ["Oladele Damilola", "40", "Nigeria"], 
        ["Alina Hricko", "23" "Ukraine"], 
        ["Isabel Walter", "50" "United Kingdom"],
    ]
    
    writer.writerow(row_list)

profiles2.py 파일에 코드를 작성한 후 명령줄 터미널로 이동하여 다음 명령을 실행합니다.

python profiles2.py

이제 작업 디렉토리에 profiles2.csv 라는 이름의 CSV 파일이 있어야 합니다 . 파일에는 row_list변수에 데이터가 있어야 합니다.

클래스를 사용하여 CSV 파일을 만드는 방법csv.DictWriter

csv.DictWriter클래스를 사용하여 사전에서 CSV 파일을 작성할 수 있습니다 . 이는 목록에서 CSV 파일에 쓰는 csv.writer 클래스와 다릅니다.

csv.DictWriter 의 구문은 다음과 같습니다.

class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

이제 구문에서 다양한 매개변수의 의미를 설명하겠습니다.

  1. 는 메소드 csvfile가 있는 파일 객체를 나타냅니다.write()
  2. 매개 fieldnames변수는 Python이 사전의 값을 전달하는 순서를 식별하는 일련의 키입니다.
  3. 매개 변수 restval는 선택사항이며 사전에 fieldnames의 키가 누락된 경우 작성될 값을 지정합니다.
  4. 매개 변수 extrasaction 는 선택 사항이며 필드 이름에서 키를 찾을 수 없는 경우 수행할 작업을 지정합니다. 이 매개변수를 로 설정하면 ValueErrorraise 가 발생합니다 .
  5. 매개 dialect변수는 선택사항이며 사용하려는 방언의 이름을 나타냅니다.

csv.DictWriter 클래스에는 데이터를 CSV 파일 쓰는 데 사용할 수 있는 두 가지 메서드가 있습니다. 방법은 다음과 같습니다.

방법 writeheader()_

writeheader() 메서드를 사용하여 사전 지정된 fieldnames.

writeheader() 메서드가 어떻게 작동하는지 확인하려면 작업 디렉터리에 profiles3.py 라는 새 파일을 만듭니다 . 그런 다음 코드 편집기를 사용하여 profles3.py 파일 에 다음 코드를 작성합니다 .

import csv 

mydict =[{'name': 'Kelvin Gates', 'age': '19', 'country': 'USA'}, 
         {'name': 'Blessing Iroko', 'age': '25', 'country': 'Nigeria'}, 
         {'name': 'Idong Essien', 'age': '42', 'country': 'Ghana'}]
         
fields = ['name', 'age', 'country'] 

with open('profiles3.csv', 'w', newline='') as file: 
    writer = csv.DictWriter(file, fieldnames = fields)
    
    writer.writeheader() 

profiles3.py 의 코드 설명은 다음과 같습니다.

  1. 첫 번째 줄은 Python csv 모듈을 가져옵니다.
  2. 두 번째 줄은 Python csv 모듈을 나머지 코드와 구분하는 빈 공간입니다.
  3. 세 번째 행은 라는 변수에 세 개의 서로 다른 사전을 포함하는 목록을 저장합니다 mydict. 사전에는 서로 다른 프로필의 데이터가 있습니다.
  4. 7행은 이라는 변수에서 만들려는 CSV 파일의 각 열 제목을 나타내는 문자열을 저장합니다 fields.
  5. 9행은 함수를 사용하여 쓰기 모드에서 profiles3.csvopen() 파일을 엽니다 .
  6. 10행의 함수 csv.DictWriter()는 CSV 사전 작성기 개체를 만듭니다.
  7. writer.writeheader()12행은 미리 정의된 필드 이름을 쓰는 함수 에 사전 목록을 전달합니다 .

코드 작성을 완료하면 명령줄 터미널로 이동하여 python 파일 profiles3.py 가 있는 디렉터리로 이동합니다 . 다음 명령을 실행합니다.

python profiles3.py

이제 작업 디렉토리에 다음 텍스트가 포함된 profiles3.csv 라는 이름의 CSV 파일을 가져와야 합니다 .

name,age,country

방법 writerows()_

writerows () 메서드는 writeheader() 메서드와 사용법이 비슷합니다. 이 방법을 사용하여 모든 행을 쓸 수 있습니다. 메서드는 값만 쓰고 키는 쓰지 않습니다.

writerows() 메서드를 사용하려면 다음 코드 줄을 profiles3.py 의 코드에 추가하세요 .

writer.writerows(mydict)

이제 작업 디렉터리에서 profiles3.csv를 삭제 하고 명령줄 터미널에서 다음 명령을 다시 실행합니다.

python profiles3.py

이제 다음 텍스트가 포함된 작업 디렉토리에 profiles3.csv 라는 이름의 새 CSV 파일이 있어야 합니다 .

name,age,country
Kelvin Gates,19,USA
Blessing Iroko,25,Nigeria
Idong Essien,42,Ghana

결론

CSV는 쉼표 에서 이름을 얻었지만 쉼표는 데이터를 구분하는 구분 기호일 뿐입니다.

쉼표는 대부분의 CSV 파일에 표시되는 인기 있는 구분 기호입니다. 그러나 구분 기호는 다른 것일 수도 있습니다. 예를 들어 쉼표 대신 세미콜론을 사용하여 데이터를 구분할 수 있습니다.

참조 및 추가 읽기

출처: https://www.freecodecamp.org

#python #csv

What is GEEK

Buddha Community

Python에서 CSV 파일을 만드는 2가지 방법
최  호민

최 호민

1677687060

Python에서 CSV 파일을 만드는 2가지 방법

csv라는 Python 내장 모듈을 사용하여 CSV 파일을 만드는 방법을 알아봅니다. Python에서 CSV 파일을 만드는 두 가지 방법: csv.DictWriter 클래스 및 csv.writer 클래스 사용

Python에서 CSV 파일을 만드는 방법은 무엇입니까? 

CSV는 쉼표로 구분된 값의 약어입니다. 스프레드시트와 같이 테이블 형식 데이터를 저장하는 데 사용할 수 있는 파일 형식입니다. 테이블 형식 데이터베이스의 데이터를 저장하는 데 사용할 수도 있습니다.

CSV 파일의 각 행을 데이터 레코드로 참조할 수 있습니다. 각 데이터 레코드는 쉼표로 구분된 하나 이상의 필드로 구성됩니다.

이 문서에서는 csv 라는 Python 내장 모듈을 사용하여 CSV 파일을 만드는 방법을 보여줍니다. 이 자습서를 완전히 이해하려면 Python 프로그래밍 언어의 기초를 잘 이해하고 있어야 합니다.

csv 모듈에는 데이터를 CSV에 쓰는 데 사용할 수 있는 두 가지 클래스가 있습니다. 이러한 클래스는 다음과 같습니다.

  • 수업 csv.writer_
  • 수업 csv.DictWriter_

클래스를 사용하여 CSV 파일을 만드는 방법csv.writer

csv.writer 클래스를 사용하여 데이터를 CSV 파일에 쓸 수 있습니다 . 이 클래스는 데이터를 구분된 문자열로 변환하는 데 사용할 수 있는 기록기 개체를 반환합니다.

인용된 필드 내의 줄 바꿈 문자가 올바르게 해석되도록 하려면 newline='' 을 사용하여 CSV 파일 개체를 엽니다 .

csv.writer 클래스 의 구문은 다음과 같습니다.

csv.writer(csvfile, dialect=’excel’, **fmtparams)

이제 구문에 사용된 다양한 매개변수의 의미를 안내해 드리겠습니다.

  1. 매개 변수 는 메서드 csvfile 가 있는 csvfile 개체를 나타냅니다 write().
  2. 선택적 dialect매개변수는 CSV 파일 작성에 사용할 수 있는 방언의 이름을 나타냅니다.
  3. 선택적 매개변수는 언어에 지정된 매개변수를 덮어쓰는 데 사용할 수 있는 형식 매개변수를 fmtparams나타냅니다 .

csv.writer 클래스에는 데이터를 CSV 파일 쓰는 데 사용할 수 있는 두 가지 메서드가 있습니다. 방법은 다음과 같습니다.

방법 writerow()_

writerow()메서드는 반복 가능한 데이터를 매개변수로 받은 다음 데이터를 단일 행의 CSV 파일에 씁니다. writerow() 메서드 의 인기 있는 사용법 중 하나 는 CSV 파일의 필드 행을 작성하는 데 사용하는 것입니다.

이제 writerow() 메서드를 사용하여 CSV 파일에 단일 행을 쓰는 방법을 보여드리겠습니다 .

코드 편집기에서 이름이 profiles1.py 인 파일을 만듭니다 . 그런 다음 파일에 다음 코드를 작성합니다.

import csv

with open('profiles1.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    field = ["name", "age", "country"]
    
    writer.writerow(field)
    writer.writerow(["Oladele Damilola", "40", "Nigeria"])
    writer.writerow(["Alina Hricko", "23", "Ukraine"])
    writer.writerow(["Isabel Walter", "50", "United Kingdom"])

코드 입력에 대한 설명은 profiles1.py다음과 같습니다.

  1. 첫 번째 줄은 Python csv 모듈을 가져옵니다.
  2. 두 번째 줄은 가져온 모듈을 나머지 코드와 구분하는 빈 줄입니다.
  3. 코드의 세 번째 줄은 함수의 도움으로 CSV 파일을 쓰기(w 모드)로 엽니다 open().
  4. 네 번째 줄은 writer() 함수를 호출하여 CSV 작성기 개체를 만들고 변수에 저장합니다 writer.
  5. fields다섯 번째 줄 은 CSV 파일의 열 제목을 각각 나타내는 문자열로 구성된 목록을 저장하는 이라는 변수를 만듭니다 .
  6. 6행 이하는 CSV Writer 객체의 writerow() 메소드를 호출하여 필드 데이터 및 기타 데이터를 CSV 파일에 씁니다.

완료되면 명령줄 터미널로 이동하여 Python 파일 profiles1.py 가 있는 디렉터리로 이동합니다 . 다음 명령을 실행합니다.

python profiles1.py

다음 텍스트가 포함된 작업 디렉토리에 profiles1.csv 라는 이름의 CSV 파일이 있어야 합니다 .

name,age,country
Oladele Damilola,40,Nigeria
Alina Hricko,23,Ukraine
Isabel Walter,50,United Kingdom

방법 writerows()_

writerows () 메서드는 writerow() 메서드와 사용법이 유사합니다. 유일한 차이점은 writerow() 메서드는 단일 행을 CSV 파일에 쓰는 반면 writerows () 메서드를 사용하면 CSV 파일에 여러 행을 쓸 수 있다는 것입니다.

writerows() 메서드의 작동 방식을 보려면 작업 디렉터리에 profiles2.py 라는 파일을 만듭니다 . 그런 다음 생성한 파일에 다음 코드를 작성합니다.

import csv

with open('profiles2.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    row_list = [
        ["name", "age", "country"], 
        ["Oladele Damilola", "40", "Nigeria"], 
        ["Alina Hricko", "23" "Ukraine"], 
        ["Isabel Walter", "50" "United Kingdom"],
    ]
    
    writer.writerow(row_list)

profiles2.py 파일에 코드를 작성한 후 명령줄 터미널로 이동하여 다음 명령을 실행합니다.

python profiles2.py

이제 작업 디렉토리에 profiles2.csv 라는 이름의 CSV 파일이 있어야 합니다 . 파일에는 row_list변수에 데이터가 있어야 합니다.

클래스를 사용하여 CSV 파일을 만드는 방법csv.DictWriter

csv.DictWriter클래스를 사용하여 사전에서 CSV 파일을 작성할 수 있습니다 . 이는 목록에서 CSV 파일에 쓰는 csv.writer 클래스와 다릅니다.

csv.DictWriter 의 구문은 다음과 같습니다.

class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

이제 구문에서 다양한 매개변수의 의미를 설명하겠습니다.

  1. 는 메소드 csvfile가 있는 파일 객체를 나타냅니다.write()
  2. 매개 fieldnames변수는 Python이 사전의 값을 전달하는 순서를 식별하는 일련의 키입니다.
  3. 매개 변수 restval는 선택사항이며 사전에 fieldnames의 키가 누락된 경우 작성될 값을 지정합니다.
  4. 매개 변수 extrasaction 는 선택 사항이며 필드 이름에서 키를 찾을 수 없는 경우 수행할 작업을 지정합니다. 이 매개변수를 로 설정하면 ValueErrorraise 가 발생합니다 .
  5. 매개 dialect변수는 선택사항이며 사용하려는 방언의 이름을 나타냅니다.

csv.DictWriter 클래스에는 데이터를 CSV 파일 쓰는 데 사용할 수 있는 두 가지 메서드가 있습니다. 방법은 다음과 같습니다.

방법 writeheader()_

writeheader() 메서드를 사용하여 사전 지정된 fieldnames.

writeheader() 메서드가 어떻게 작동하는지 확인하려면 작업 디렉터리에 profiles3.py 라는 새 파일을 만듭니다 . 그런 다음 코드 편집기를 사용하여 profles3.py 파일 에 다음 코드를 작성합니다 .

import csv 

mydict =[{'name': 'Kelvin Gates', 'age': '19', 'country': 'USA'}, 
         {'name': 'Blessing Iroko', 'age': '25', 'country': 'Nigeria'}, 
         {'name': 'Idong Essien', 'age': '42', 'country': 'Ghana'}]
         
fields = ['name', 'age', 'country'] 

with open('profiles3.csv', 'w', newline='') as file: 
    writer = csv.DictWriter(file, fieldnames = fields)
    
    writer.writeheader() 

profiles3.py 의 코드 설명은 다음과 같습니다.

  1. 첫 번째 줄은 Python csv 모듈을 가져옵니다.
  2. 두 번째 줄은 Python csv 모듈을 나머지 코드와 구분하는 빈 공간입니다.
  3. 세 번째 행은 라는 변수에 세 개의 서로 다른 사전을 포함하는 목록을 저장합니다 mydict. 사전에는 서로 다른 프로필의 데이터가 있습니다.
  4. 7행은 이라는 변수에서 만들려는 CSV 파일의 각 열 제목을 나타내는 문자열을 저장합니다 fields.
  5. 9행은 함수를 사용하여 쓰기 모드에서 profiles3.csvopen() 파일을 엽니다 .
  6. 10행의 함수 csv.DictWriter()는 CSV 사전 작성기 개체를 만듭니다.
  7. writer.writeheader()12행은 미리 정의된 필드 이름을 쓰는 함수 에 사전 목록을 전달합니다 .

코드 작성을 완료하면 명령줄 터미널로 이동하여 python 파일 profiles3.py 가 있는 디렉터리로 이동합니다 . 다음 명령을 실행합니다.

python profiles3.py

이제 작업 디렉토리에 다음 텍스트가 포함된 profiles3.csv 라는 이름의 CSV 파일을 가져와야 합니다 .

name,age,country

방법 writerows()_

writerows () 메서드는 writeheader() 메서드와 사용법이 비슷합니다. 이 방법을 사용하여 모든 행을 쓸 수 있습니다. 메서드는 값만 쓰고 키는 쓰지 않습니다.

writerows() 메서드를 사용하려면 다음 코드 줄을 profiles3.py 의 코드에 추가하세요 .

writer.writerows(mydict)

이제 작업 디렉터리에서 profiles3.csv를 삭제 하고 명령줄 터미널에서 다음 명령을 다시 실행합니다.

python profiles3.py

이제 다음 텍스트가 포함된 작업 디렉토리에 profiles3.csv 라는 이름의 새 CSV 파일이 있어야 합니다 .

name,age,country
Kelvin Gates,19,USA
Blessing Iroko,25,Nigeria
Idong Essien,42,Ghana

결론

CSV는 쉼표 에서 이름을 얻었지만 쉼표는 데이터를 구분하는 구분 기호일 뿐입니다.

쉼표는 대부분의 CSV 파일에 표시되는 인기 있는 구분 기호입니다. 그러나 구분 기호는 다른 것일 수도 있습니다. 예를 들어 쉼표 대신 세미콜론을 사용하여 데이터를 구분할 수 있습니다.

참조 및 추가 읽기

출처: https://www.freecodecamp.org

#python #csv

Vincent Lab

Vincent Lab

1605178770

Working with CSV in JavaScript

In this video I’m going to be showing you how to work with CSV files in Node.js

#csv #node.js #working with data #csv file #nodejs load csv file #tutorial

Laravel 8 Import Export CSV/EXCEL File Example

In this post i will show you Laravel 8 Import Export CSV/EXCEL File Example. We will simple create import data to xls, csv file and also we will import data to database using csv file in laravel 8 application.

Using this example we can easily import-export and download the csv & excel file from the database using the maatwebsite/excel composer package. maatwebsite/excel provide easy way to import and export csv file in laravel 8 using database model.

Laravel 8 Import Export CSV/EXCEL File Example

https://websolutionstuff.com/post/laravel-8-import-export-csv-excel-file-example

#laravel 8 import export csv/excel file example #laravel 8 #import #export #csv/excel #import and export csv file in laravel 8

Duck Hwan

1667824401

Python에서 CSV 파일을 읽고 쓰는 방법

이 기사에서는 Python을 사용하여 CSV 파일을 읽고 쓰는 방법에 대한 자습서를 안내합니다. 이 기사에서는 Python에서 pandas 라이브러리를 사용하여 CSV 파일을 읽고 쓰는 방법을 알려줍니다.

여기에서 먼저 학생의 이름과 나이에 대한 Python 사전을 사용하여 샘플 데이터를 만든 다음 해당 Python 사전을 CSV 파일에 저장합니다.

# writing a csv file
import csv
import pandas as pd
data = {"Name": ["Jacks", "Tom", "Thomas", "Oscar", "Marry"], 
        "Age": [23, 21, 25, 23, 22]}
data = pd.DataFrame(data)
data.to_csv("age_data.csv", index=False)
print(data.head())

산출:

       Name  Age
0      Jacks   23
1      Tom     21
2      Thomas  25
3      Oscar   23  
4      Marry   22

이것이 Python을 사용하여 CSV 파일을 작성하는 방법입니다. 이제 아래는 Python을 사용하여 이 CSV 파일을 읽는 방법입니다.

# reading a csv file
import pandas as pd
data = pd.read_csv("age_data.csv")
print(data.head())

산출

       Name  Age
0      Jacks   23
1      Tom     21
2      Thomas  25
3      Oscar   23  
4      Marry   22

이것이 Python의 pandas 라이브러리를 사용하여 CSV 파일을 읽고 쓰는 것이 얼마나 쉬운지 보여줍니다.

CSV-parser: Streaming Csv Parser inspired By Binary-csv

csv-parser  

Streaming CSV parser that aims for maximum speed as well as compatibility with the csv-spectrum CSV acid test suite.

csv-parser can convert CSV into JSON at at rate of around 90,000 rows per second. Performance varies with the data used; try bin/bench.js <your file> to benchmark your data.

csv-parser can be used in the browser with browserify.

neat-csv can be used if a Promise based interface to csv-parser is needed.

Note: This module requires Node v8.16.0 or higher.

Benchmarks

⚡️ csv-parser is greased-lightning fast

→ npm run bench

  Filename                 Rows Parsed  Duration
  backtick.csv                       2     3.5ms
  bad-data.csv                       3    0.55ms
  basic.csv                          1    0.26ms
  comma-in-quote.csv                 1    0.29ms
  comment.csv                        2    0.40ms
  empty-columns.csv                  1    0.40ms
  escape-quotes.csv                  3    0.38ms
  geojson.csv                        3    0.46ms
  large-dataset.csv               7268      73ms
  newlines.csv                       3    0.35ms
  no-headers.csv                     3    0.26ms
  option-comment.csv                 2    0.24ms
  option-escape.csv                  3    0.25ms
  option-maxRowBytes.csv          4577      39ms
  option-newline.csv                 0    0.47ms
  option-quote-escape.csv            3    0.33ms
  option-quote-many.csv              3    0.38ms
  option-quote.csv                   2    0.22ms
  quotes+newlines.csv                3    0.20ms
  strict.csv                         3    0.22ms
  latin.csv                          2    0.38ms
  mac-newlines.csv                   2    0.28ms
  utf16-big.csv                      2    0.33ms
  utf16.csv                          2    0.26ms
  utf8.csv                           2    0.24ms

Install

Using npm:

$ npm install csv-parser

Using yarn:

$ yarn add csv-parser

Usage

To use the module, create a readable stream to a desired CSV file, instantiate csv, and pipe the stream to csv.

Suppose you have a CSV file data.csv which contains the data:

NAME,AGE
Daffy Duck,24
Bugs Bunny,22

It could then be parsed, and results shown like so:

const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results);
    // [
    //   { NAME: 'Daffy Duck', AGE: '24' },
    //   { NAME: 'Bugs Bunny', AGE: '22' }
    // ]
  });

To specify options for csv, pass an object argument to the function. For example:

csv({ separator: '\t' });

API

csv([options | headers])

Returns: Array[Object]

options

Type: Object

As an alternative to passing an options object, you may pass an Array[String] which specifies the headers to use. For example:

csv(['Name', 'Age']);

If you need to specify options and headers, please use the the object notation with the headers property as shown below.

escape

Type: String
Default: "

A single-character string used to specify the character used to escape strings in a CSV row.

headers

Type: Array[String] | Boolean

Specifies the headers to use. Headers define the property key for each value in a CSV row. If no headers option is provided, csv-parser will use the first line in a CSV file as the header specification.

If false, specifies that the first row in a data file does not contain headers, and instructs the parser to use the column index as the key for each column. Using headers: false with the same data.csv example from above would yield:

[
  { '0': 'Daffy Duck', '1': 24 },
  { '0': 'Bugs Bunny', '1': 22 }
]

Note: If using the headers for an operation on a file which contains headers on the first line, specify skipLines: 1 to skip over the row, or the headers row will appear as normal row data. Alternatively, use the mapHeaders option to manipulate existing headers in that scenario.

mapHeaders

Type: Function

A function that can be used to modify the values of each header. Return a String to modify the header. Return null to remove the header, and it's column, from the results.

csv({
  mapHeaders: ({ header, index }) => header.toLowerCase()
})

Parameters

header String The current column header.
index Number The current column index.

mapValues

Type: Function

A function that can be used to modify the content of each column. The return value will replace the current column content.

csv({
  mapValues: ({ header, index, value }) => value.toLowerCase()
})

Parameters

header String The current column header.
index Number The current column index.
value String The current column value (or content).

newline

Type: String
Default: \n

Specifies a single-character string to denote the end of a line in a CSV file.

quote

Type: String
Default: "

Specifies a single-character string to denote a quoted string.

raw

Type: Boolean
 

If true, instructs the parser not to decode UTF-8 strings.

separator

Type: String
Default: ,

Specifies a single-character string to use as the column separator for each row.

skipComments

Type: Boolean | String
Default: false

Instructs the parser to ignore lines which represent comments in a CSV file. Since there is no specification that dictates what a CSV comment looks like, comments should be considered non-standard. The "most common" character used to signify a comment in a CSV file is "#". If this option is set to true, lines which begin with # will be skipped. If a custom character is needed to denote a commented line, this option may be set to a string which represents the leading character(s) signifying a comment line.

skipLines

Type: Number
Default: 0

Specifies the number of lines at the beginning of a data file that the parser should skip over, prior to parsing headers.

maxRowBytes

Type: Number
Default: Number.MAX_SAFE_INTEGER

Maximum number of bytes per row. An error is thrown if a line exeeds this value. The default value is on 8 peta byte.

strict

Type: Boolean
Default: false

If true, instructs the parser that the number of columns in each row must match the number of headers specified or throws an exception. if false: the headers are mapped to the column index less columns: any missing column in the middle will result in a wrong property mapping! more columns: the aditional columns will create a "_"+index properties - eg. "_10":"value"

Events

The following events are emitted during parsing:

data

Emitted for each row of data parsed with the notable exception of the header row. Please see Usage for an example.

headers

Emitted after the header row is parsed. The first parameter of the event callback is an Array[String] containing the header names.

fs.createReadStream('data.csv')
  .pipe(csv())
  .on('headers', (headers) => {
    console.log(`First header: ${headers[0]}`)
  })

Readable Stream Events

Events available on Node built-in Readable Streams are also emitted. The end event should be used to detect the end of parsing.

CLI

This module also provides a CLI which will convert CSV to newline-delimited JSON. The following CLI flags can be used to control how input is parsed:

Usage: csv-parser [filename?] [options]

  --escape,-e         Set the escape character (defaults to quote value)
  --headers,-h        Explicitly specify csv headers as a comma separated list
  --help              Show this help
  --output,-o         Set output file. Defaults to stdout
  --quote,-q          Set the quote character ('"' by default)
  --remove            Remove columns from output by header name
  --separator,-s      Set the separator character ("," by default)
  --skipComments,-c   Skip CSV comments that begin with '#'. Set a value to change the comment character.
  --skipLines,-l      Set the number of lines to skip to before parsing headers
  --strict            Require column length match headers length
  --version,-v        Print out the installed version

For example; to parse a TSV file:

cat data.tsv | csv-parser -s $'\t'

Encoding

Users may encounter issues with the encoding of a CSV file. Transcoding the source stream can be done neatly with a modules such as:

Or native iconv if part of a pipeline.

Byte Order Marks

Some CSV files may be generated with, or contain a leading Byte Order Mark. This may cause issues parsing headers and/or data from your file. From Wikipedia:

The Unicode Standard permits the BOM in UTF-8, but does not require nor recommend its use. Byte order has no meaning in UTF-8.

To use this module with a file containing a BOM, please use a module like strip-bom-stream in your pipeline:

const fs = require('fs');

const csv = require('csv-parser');
const stripBom = require('strip-bom-stream');

fs.createReadStream('data.csv')
  .pipe(stripBom())
  .pipe(csv())
  ...

When using the CLI, the BOM can be removed by first running:

$ sed $'s/\xEF\xBB\xBF//g' data.csv

Download Details:

Author: Mafintosh
Source Code: https://github.com/mafintosh/csv-parser 
License: MIT license

#javascript #csv #streaming