0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[csv加工]csvファイルの空白スペースを削除し、カンマを追加

Posted at

変数 考え方

csvデータのカンマ空白を入れる配列を用意 : cleaned_data = []

カンマつける変数 : formatted_row

空きスペースを消す変数 : cleaned_row

加工前データ : row

加工後データ : formatted_row

code

import csv
import re
from openpyxl import load_workbook

def clean_and_format_csv(file_path):
    cleaned_data = []

    with open(file_path, 'r', encoding='utf-8') as infile:
        reader = csv.reader(infile)
        for row in reader:
            # 1. 各セルの中で全角スペースを半角スペースに変換
            cleaned_row = [re.sub(r'\s+', ' ', cell.replace("\u3000", " ")).strip() for cell in row]

            # 2. 各セル内のスペースをカンマに変換
            formatted_row = ",".join([cell.replace(" ", ",") for cell in cleaned_row])

            print(f'Before: {row} -> After: {formatted_row}')  # デバッグ表示
            cleaned_data.append(formatted_row)

    # 3. 新しいCSVファイルに書き込み
    with open(file_path, 'w', encoding='utf-8', newline='') as outfile:
        for line in cleaned_data:
            outfile.write(line + "\n")  # 各行の末尾に改行をつけて書き込む

# 使用例
csv_file = 'meisai.csv'  # 処理するCSVファイル
clean_and_format_csv(csv_file)
print(f'成功 {csv_file}')

解説

ファイルを開け、csv読み込み
with open(file_path, 'r', encoding='utf-8') as infile:
        reader = csv.reader(infile)
から配列 用意
   cleaned_data = []
半角スペースにしたデータをカンマにする
",".join([cell.replace(" ", ",")for cell in つけたい変数名])
カンマつけたデータを配列に加える
cleaned_data.append(formatted_row)
csv保存
with open(file_path, 'w', encoding='utf-8', newline='') as outfile:
データを改行し、csvに書き込む
for line in cleaned_data:
            outfile.write(line + "\n") 
保存したいcsvを読み込み、カンマとスペースを消す処理実行
csv_file = 'meisai.csv'  # 処理するCSVファイル
clean_and_format_csv(csv_file)           
加工前データrowと、加工後データfoematted_row 確認
:print(f'Before: {row} -> After: {formatted_row}') 

CSVファイル 入出力がうまくできない原因

  • csvの先頭にタイトル ❌
  • カンマがついてない
  • 全角・半角の空きスペースが消せてない

openpyxl codeが動かない原因

  • ヘッダースキップできてない
  • 列(日付)と名前を指定している
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?