Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python - อ่านไฟล์ CSV ทั้งหมดในโฟลเดอร์ด้วย Pandas และ Glob

โมดูล glob ใช้ค้นหาไฟล์ตาม pattern (wildcard) ร่วมกับ pd.read_csv() เพื่ออ่านไฟล์ CSV หลายไฟล์ในโฟลเดอร์อัตโนมัติ

ขั้นตอนการทำงาน

1. นำเข้าไลบรารี

import pandas as pd
import glob

2. กำหนด path และหาไฟล์ .csv

path = r"C:\Users\amit_\Desktop\MyProject\"
filenames = glob.glob(path + "*.csv")

3. วนลูปอ่านและประมวลผลแต่ละไฟล์

for file in filenames:
    print(f"\nReading file: {file}")
    df = pd.read_csv(file)
    print(df)
    # ประมวลผลต่อที่นี่...

โค้ดตัวอย่างสมบูรณ์

import pandas as pd
import glob

# Path ของโฟลเดอร์
path = r"C:\Users\amit_\Desktop\MyProject\"

# หาไฟล์ .csv ทั้งหมด
filenames = glob.glob(path + "*.csv")
print('File names:', filenames)

# วนลูปอ่านทุกไฟล์
for file in filenames:
    print(f"\nReading file = {file}")
    df = pd.read_csv(file)
    print(df)

ผลลัพธ์ตัวอย่าง

File names: ['C:\\Users\\amit_\\Desktop\\MyProject\\Sales1.csv', 'C:\\Users\\amit_\\Desktop\\MyProject\\Sales2.csv']

Reading file = C:\Users\amit_\Desktop\MyProject\Sales1.csv
      Car    Place  UnitsSold
0    Audi  Bangalore         80
1  Porsche     Mumbai        110
2 RollsRoyce      Pune        100

Reading file = C:\Users\amit_\Desktop\MyProject\Sales2.csv
      Car     Place  UnitsSold
0    BMW     Delhi          95
1 Mercedes  Hyderabad         80
2 Lamborghini Chandigarh         80

รวมไฟล์ทั้งหมดเป็น DataFrame เดียว

# วิธี 1: List comprehension + concat (แนะนำ)
dfs = [pd.read_csv(f) for f in filenames]
combined = pd.concat(dfs, ignore_index=True)

# วิธี 2: Generator + concat (ประหยัดหน่วยความจำ)
combined = pd.concat((pd.read_csv(f) for f in filenames), ignore_index=True)

# วิธี 3: ใช้ map (เหมือนตัวอย่างเดิม)
combined = pd.concat(map(pd.read_csv, filenames), ignore_index=True)

Glob Patterns ที่ใช้บ่อย

Patternความหมาย
*.csvไฟล์ .csv ทั้งหมดในโฟลเดอร์
**/*.csvรวม subfolders (ต้อง recursive=True)
sales_*.csvไฟล์ขึ้นต้นด้วย sales_
*_2023.csvไฟล์จบด้วย _2023.csv
data[0-9].csvdata0.csv, data1.csv, ...

⚠️ ข้อควรระวัง

  • ใช้ r"path" (raw string) หรือ "path\\\\" (double backslash) ใน Windows
  • ตรวจสอบ encoding: pd.read_csv(f, encoding='utf-8') หรือ 'cp874' (Thai)
  • ไฟล์ใหญ่: ใช้ chunksize อ่านทีละชิ้น
  • คอลัมน์ไม่ตรงกัน: pd.concat(..., sort=False) หรือจัดการก่อน concat

Pathlib (Modern Alternative)

from pathlib import Path

path = Path(r"C:\Users\amit_\Desktop\MyProject")
csv_files = path.glob("*.csv")

for file in csv_files:
    df = pd.read_csv(file)
    # process...