Skip to content

Instantly share code, notes, and snippets.

@pypeach
Last active July 23, 2018 13:15
Show Gist options
  • Save pypeach/ef2efaf6b27992ac8740700e75306dc1 to your computer and use it in GitHub Desktop.
Save pypeach/ef2efaf6b27992ac8740700e75306dc1 to your computer and use it in GitHub Desktop.
CSV書き込みを行うサンプルアプリケーションです
# coding:utf-8
import csv
import logging
import os
from app.app_logic_base import AppLogicBase
from app.sql import employees
from app.util import app_config, message_access, date_helper
"""
CSVファイル書き込みを行うサンプルアプリケーションです
"""
__author__ = "t.ebinuma"
__version__ = "1.1"
__date__ = "28 April 2018"
class WriteCsvFile(AppLogicBase):
def __init__(self):
super().__init__()
# loggerを設定する
self.logger = logging.getLogger(__name__)
# ファイル出力先パス
self.csv_file = os.path.join(app_config.get_value("data_path"), 'write_file.csv')
def write_csv_file(self):
"""
テーブルを読み込みCSVファイルを出力する
"""
# テーブルからレコードを検索する
employees_list = employees.select([])
# CSVファイルを出力する。OS環境によって改行コードを変更する
with open(self.csv_file, 'w', encoding='UTF-8', newline='\n') as f:
if len(employees_list) > 0:
file_writer = csv.writer(f, delimiter=',', lineterminator='\n')
for employees_item in employees_list:
csv_list = [employees_item['emp_no'],
employees_item['first_name'],
employees_item['last_name'],
employees_item['gender'],
date_helper.convert_string_to_date(employees_item['birth_date'], '%Y-%m-%d').strftime(
date_helper.format_ymd),
date_helper.convert_string_to_date(employees_item['hire_date'], '%Y-%m-%d').strftime(
date_helper.format_ymd)]
self.logger.debug("csv_list={}".format(csv_list))
file_writer.writerow(csv_list)
else:
self.logger.info(message_access.get_message('I906'), "employees")
f.write("")
def main():
app_class = WriteCsvFile()
app_class.write_csv_file()
if __name__ == '__main__':
main()
@pypeach
Copy link
Author

pypeach commented May 15, 2018

親クラス(AppLogicBase)を追加

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment