search
HomeBackend DevelopmentPython TutorialGuide to Python&#s CSV Module

Guide to Python

データの操作はプログラミングでは避けられない部分であり、さまざまなファイル形式に深く関わることが多い私は、Python がどのようにプロセス全体を簡素化するかを常に高く評価してきました。

特にデータ分析において定期的に登場するファイル形式の 1 つが CSV ファイルです。

CSV (カンマ区切り値) は、そのシンプルさから一般的なデータ交換形式です。

幸いなことに、Python には csv と呼ばれる組み込みモジュールが付属しており、これらのファイルの操作が非常に効率的になります。

この記事では、基本的な使用方法から、データ処理の時間を大幅に節約できるより高度なテクニックまで、Python での csv モジュールの仕組みを詳しく説明します。


CSVファイルとは何ですか?

csv モジュールに入る前に、CSV ファイルとは何かについての基本的な理解から始めましょう。

CSV ファイルは基本的にプレーン テキスト ファイルで、各行がデータの行を表し、各値がカンマ (場合によってはタブなどの他の区切り文字) で区切られています。

これがどのようなものになるかの簡単な例を次に示します。

Name,Age,Occupation
Alice,30,Engineer
Bob,25,Data Scientist
Charlie,35,Teacher

なぜ csv モジュールなのか?

CSV ファイルは理論的には Python の標準ファイル処理メソッドを使用して読み取れる単なるテキスト ファイルであるのに、なぜ csv モジュールが必要なのか疑問に思われるかもしれません。

これは事実ですが、CSV ファイルには、埋め込まれたカンマ、セル内の改行、さまざまな区切り文字など、手動で処理するのが難しい複雑な要素が含まれる場合があります。

csv モジュールはこれらすべてを抽象化し、データに集中できるようにします。


CSVファイルの読み込み

コードの説明に入りましょう。

CSV ファイルに対して実行する最も一般的な操作は、その内容を読み取ることです。

モジュール内の csv.reader() 関数は、そのための使いやすいツールです。

これを行う方法についてのステップバイステップのガイドを次に示します。

基本的な CSV の読み取り

import csv

# Open a CSV file
with open('example.csv', 'r') as file:
    reader = csv.reader(file)

    # Iterate over the rows
    for row in reader:
        print(row)

これは CSV ファイルを読み取る最も簡単な方法です。

csv.reader() は反復可能を返し、各反復でファイルの行を表すリストが得られます。

ヘッダーの処理
ほとんどの CSV ファイルには、最初の行に列名などのヘッダーが付いています。

これらのヘッダーが必要ない場合は、反復処理時に最初の行を単純にスキップできます。

import csv

with open('example.csv', 'r') as file:
    reader = csv.reader(file)

    # Skip header
    next(reader)

    for row in reader:
        print(row)

時々、有用なデータと無関係なデータが混在するファイルを操作していると、ヘッダー以外の部分に基づいて行をスキップしていることに気づきます。

これは for ループ内で簡単に実行できます。

DictReader: CSV ファイルを読み取るためのより直感的な方法
CSV ファイルにヘッダーがある場合、 csv.DictReader() は、列名をキーとして各行を辞書として読み取るもう 1 つの素晴らしいオプションです。

import csv

with open('example.csv', 'r') as file:
    reader = csv.DictReader(file)

    for row in reader:
        print(row)

このアプローチにより、特に大規模なデータセットを扱う場合に、コードがより読みやすく直感的になりやすくなります。

たとえば、row['Name'] へのアクセスは、row[0] のようなインデックスベースのアクセスを扱うよりもはるかに明確に感じられます。


CSVファイルへの書き込み

データを読み取って処理したら、おそらくそれを保存またはエクスポートしたくなるでしょう。

csv.writer() 関数は、CSV ファイルに書き込むための頼りになるツールです。

基本的な CSV の書き方

import csv

# Data to be written
data = [
    ['Name', 'Age', 'Occupation'],
    ['Alice', 30, 'Engineer'],
    ['Bob', 25, 'Data Scientist'],
    ['Charlie', 35, 'Teacher']
]

# Open a file in write mode
with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)

    # Write data to the file
    writer.writerows(data)

writer.writerows() 関数は、リストのリストを取得して CSV ファイルに書き込みます。各内部リストはデータ行を表します。

DictWriter: CSV ファイルを作成するためのよりクリーンな方法
CSV ファイルを辞書に読み取るための DictReader があるのと同じように、CSV に辞書を書き込むための DictWriter があります。

このメソッドは、列名を明示的に指定する場合に特に便利です。

import csv

# Data as list of dictionaries
data = [
    {'Name': 'Alice', 'Age': 30, 'Occupation': 'Engineer'},
    {'Name': 'Bob', 'Age': 25, 'Occupation': 'Data Scientist'},
    {'Name': 'Charlie', 'Age': 35, 'Occupation': 'Teacher'}
]

# Open file for writing
with open('output.csv', 'w', newline='') as file:
    fieldnames = ['Name', 'Age', 'Occupation']
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    # Write the header
    writer.writeheader()

    # Write the data
    writer.writerows(data)

DictWriter を使用すると、コードを読みやすく簡潔に保ちながら、CSV に辞書を書き込むための美しくクリーンなインターフェイスが得られます。


区切り文字のカスタマイズ

デフォルトでは、CSV モジュールはカンマを使用して値を区切りますが、タブやセミコロンなどの他の区切り文字を使用するファイルを操作している場合もあります。

csv モジュールは、区切り文字引数を指定することで、これらのケースを簡単に処理する方法を提供します。

import csv

with open('example_tab.csv', 'r') as file:
    reader = csv.reader(file, delimiter='\t')

    for row in reader:
        print(row)

カンマの代わりにセミコロンを使用する CSV ファイル (通常はヨーロッパのソースからのもの) を見つけましたが、Python の csv モジュールがこれを簡単に処理できることを知って安心しました。

カンマ、タブ、その他の区切り文字であっても、csv モジュールが対応します。


複雑なデータの処理

データのフィールド内にカンマ、引用符、さらには改行が含まれている場合はどうなりますか?

CSV モジュールは、引用メカニズムを使用してこのようなケースを自動的に処理します。

引用パラメーターを使用して、引用の動作を制御することもできます。

import csv

data = [
    ['Name', 'Occupation', 'Description'],
    ['Alice', 'Engineer', 'Works on, "cutting-edge" technology'],
    ['Bob', 'Data Scientist', 'Loves analyzing data.']
]

with open('complex.csv', 'w', newline='') as file:
    writer = csv.writer(file, quoting=csv.QUOTE_ALL)
    writer.writerows(data)

In this example, QUOTE_ALL ensures that every field is wrapped in quotes.

Other quoting options include csv.QUOTE_MINIMAL, csv.QUOTE_NONNUMERIC, and csv.QUOTE_NONE, giving you full control over how your CSV data is formatted.


Conclusion

Over the years, I’ve come to rely on the CSV format as a lightweight, efficient way to move data around, and Python’s csv module has been a trusty companion in that journey.

Whether you’re dealing with simple spreadsheets or complex, multi-line data fields, this module makes the process feel intuitive and effortless.

While working with CSVs may seem like a mundane task at first, it’s a gateway to mastering data manipulation.

In my experience, once you’ve conquered CSVs, you'll find yourself confidently tackling larger, more complex formats like JSON or SQL databases. After all, everything starts with the basics.

The above is the detailed content of Guide to Python&#s CSV Module. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools