Home Backend Development Python Tutorial Guide to Python&#s CSV Module

Guide to Python&#s CSV Module

Oct 11, 2024 am 10:17 AM

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
Copy after login

なぜ 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)
Copy after login

これは 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)
Copy after login

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

これは 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)
Copy after login

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

たとえば、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)

Copy after login

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)
Copy after login

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)
Copy after login

カンマの代わりにセミコロンを使用する 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)
Copy after login

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1667
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python vs. C  : Exploring Performance and Efficiency Python vs. C : Exploring Performance and Efficiency Apr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Which is part of the Python standard library: lists or arrays? Which is part of the Python standard library: lists or arrays? Apr 27, 2025 am 12:03 AM

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Learning Python: Is 2 Hours of Daily Study Sufficient? Learning Python: Is 2 Hours of Daily Study Sufficient? Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python vs. C  : Understanding the Key Differences Python vs. C : Understanding the Key Differences Apr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

See all articles