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: data_list.append(pd.read_csv(file, encoding=”cp932″)) except UnicodeDecodeError: try: data_list.append(pd.read_csv(file, encoding=”shift-jis”)) except UnicodeDecodeError: data_list.append(pd.read_csv(file, encoding=”utf-8″)) except pd.errors.ParserError: # XLRDErrorが発生する可能性があるため、ParserErrorに変更 data_list.append(pd.read_excel(file, encoding=”cp932″)) df = pd.concat(data_list, axis=0) t_delta = datetime.timedelta(hours=9) JST = datetime.timezone(t_delta, ‘JST’) now_jst = datetime.datetime.now(JST) now = now_jst.strftime(‘%Y%m%d%H%M%S’) 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 HttpResponse(‘Files uploaded successfully.’) return render(request, ‘tools/concat_csv.html’ ) ファイルを連結して出力したい

あなたのコードは、複数のCSVファイルを受け取り、それらを読み込んでDataFrameとして連結し、最終的に1つのCSVファイルとして出力しています。ただし、いくつかのポイントについて留意する必要があります。

  1. output_pathの指定:
    出力先のファイルパスを指定する際、絶対パスを使用しています。これはサーバー上の特定のディレクトリに保存する場合に便利です。ただし、相対パスを使用することもでき、その場合はプロジェクトのルートディレクトリからの相対パスとなります。

  2. content_typeの指定:
    レスポンスのcontent_typeには、実際のファイルの種類に合わせて正確なMIMEタイプを指定することが良いでしょう。CSVファイルの場合、text/csvを指定することが一般的です。

以下は、一部修正を含んだコード例です。

python
import os 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') print(files) data_list = [] for file in files: try: data_list.append(pd.read_csv(file, encoding="cp932")) except UnicodeDecodeError: try: data_list.append(pd.read_csv(file, encoding="shift-jis")) except UnicodeDecodeError: data_list.append(pd.read_csv(file, encoding="utf-8")) except pd.errors.ParserError: # XLRDErrorが発生する可能性があるため、ParserErrorに変更 data_list.append(pd.read_excel(file, encoding="cp932")) df = pd.concat(data_list, axis=0) t_delta = datetime.timedelta(hours=9) JST = datetime.timezone(t_delta, 'JST') now_jst = datetime.datetime.now(JST) now = now_jst.strftime('%Y%m%d%H%M%S') output_path = f"media/Concat_data_{now}.csv" # mediaディレクトリに保存する例 df.to_csv(output_path, index=False, encoding="cp932", errors="ignore") # ファイルのダウンロードを促すレスポンスを返す with open(output_path, 'rb') as file: response = HttpResponse(file.read(), content_type='text/csv') response['Content-Disposition'] = f'attachment; filename={os.path.basename(output_path)}' return response return render(request, 'tools/concat_csv.html')

上記の例では、mediaディレクトリに結合されたCSVファイルを保存しています。また、content_typetext/csvに変更しています。必要に応じて、保存先やMIMEタイプをプロジェクトの要件に合わせて調整してください。

未分類

Posted by ぼっち