def concat_csv(request): if request.method == ‘POST’ and request.FILES.getlist(‘files’): files = request.FILES.getlist(‘files’) print(files) data_list = [] for file in files: try: with file.open(‘rb’) as f: # ファイルの中身を一部読み取ってエンコーディングを判定 result = chardet.detect(f.read(10000)) detected_encoding = result[‘encoding’] confidence = result[‘confidence’] print(f”Detected encoding: {detected_encoding}, Confidence: {confidence}”) # ファイルを再度開いてから読み込み with file.open(‘rb’) as f: # ファイルがCSVかどうかのチェックも追加 if file.name.endswith(‘.csv’): try: df = pd.read_csv(f, encoding=detected_encoding) data_list.append(df) except UnicodeDecodeError as e: print(f”UnicodeDecodeError: {e}”) print(“Failed to read CSV file even with detected encoding.”) except pd.errors.EmptyDataError: print(“CSV file is empty.”) else: print(f”Unsupported file format: {file.name}”) except Exception as e: print(f”Error: {e}”) # データが1つ以上ある場合にのみ pd.concat を実行 if data_list: df = pd.concat(data_list, axis=0) # 以下、データフレームの後続の処理を行う(例:CSVに保存、レスポンスとして返すなど) # 保存先のパスを指定(適切なパスを設定してください) output_path = “/Concat_data.csv” # ファイルの保存 df.to_csv(output_path, index=False, encoding=”cp932″, errors=”ignore”) # ファイルのダウンロードを促すレスポンスを返す with open(output_path, ‘rb’) as file: response = HttpResponse(file.read(), content_type=’application/force-download’) response[‘Content-Disposition’] = f’attachment; filename={os.path.basename(output_path)}’ return response return render(request, ‘tools/concat_csv.html’)
このコードは、CSVファイルをアップロードして連結し、それをダウンロードする Django ビューのようですね。コードにはいくつかの問題が見受けられますが、まず最初にファイルを読み込んで連結する部分に焦点を当ててみましょう。
以下は、修正として提案されるコードの一部です。これは、エンコーディングの自動判定、CSVファイルの読み込み、連結、保存を行うものです。エラーのデバッグ情報も含まれています。
python
import chardet import pandas as pd from django.http import HttpResponse from django.shortcuts import render def concat_csv(request): if request.method == 'POST' and request.FILES.getlist('files'): files = request.FILES.getlist('files') data_list = [] for file in files: try: with file.open('rb') as f: # ファイルの中身を一部読み取ってエンコーディングを判定 result = chardet.detect(f.read(10000)) detected_encoding = result['encoding'] confidence = result['confidence'] print(f"Detected encoding: {detected_encoding}, Confidence: {confidence}") # ファイルを再度開いてから読み込み with file.open('r', encoding=detected_encoding) as f: # ファイルがCSVかどうかのチェックも追加 if file.name.endswith('.csv'): try: df = pd.read_csv(f) data_list.append(df) except UnicodeDecodeError as e: print(f"UnicodeDecodeError: {e}") print("Failed to read CSV file even with detected encoding.") except pd.errors.EmptyDataError: print("CSV file is empty.") else: print(f"Unsupported file format: {file.name}") except Exception as e: print(f"Error: {e}") # データが1つ以上ある場合にのみ pd.concat を実行 if data_list: df = pd.concat(data_list, axis=0) # 以下、データフレームの後続の処理を行う(例:CSVに保存、レスポンスとして返すなど) # 保存先のパスを指定(適切なパスを設定してください) output_path = "Concat_data.csv" # ファイルの保存 df.to_csv(output_path, index=False, encoding="cp932", errors="ignore") # ファイルのダウンロードを促すレスポンスを返す with open(output_path, 'rb') as file: response = HttpResponse(file.read(), content_type='application/force-download') response['Content-Disposition'] = f'attachment; filename={os.path.basename(output_path)}' return response return render(request, 'tools/concat_csv.html')
修正点:
file.open('r', encoding=detected_encoding)にて、encodingパラメータを使用してファイルを開くようにしました。- ファイルがCSV形式でない場合のエラー処理を追加しました。
この修正を試してみてください。何か問題があれば、エラーメッセージや挙動について教えてください。

ディスカッション
コメント一覧
まだ、コメントがありません