LoginSignup
0
0

More than 3 years have passed since last update.

Pythonでよく使う機能のモジュール(外部ファイル読み取りとか)

Posted at

初めに

自分用に作ったものなので、使い道は限られていると思います。
外部ファイルを設定用にプログラムから読んだりすることが多いので、簡単にできるようにまとめてあります。
ついでにDatetimeの扱いもややこしいのでまとめてあったり。
モジュール化、使い方に関しては、以下の記事が詳しく書かれていますのでご覧ください。

pythonで自作関数をモジュール化・パッケージ化 - Qiita

モジュール

MyModule.py
# -*- coding: utf-8 -*-
import time, shutil, os, sys, datetime

class File:
    # ファイルを読み取ってリストとして返す(エラーの場合"error"を返す)
    def ReadListOut(path):
        try:
            with open(path,'r',encoding="utf-8") as f:
                Sentence = [s.strip() for s in f.readlines()]
                return Sentence
        except FileNotFoundError:
            return "error"

    # リスト型のデータを改行しながら書き込み
    def WriteListIn(path, Sentence):
        Sentence = "\n" + '\n'.join(list(map(str, Sentence)))
        with open(path, mode='a',encoding="utf-8") as f:
            f.writelines(Sentence)

    # 一行の文章を改行してから書き込み
    def WriteStrIn(path, Sentence):
        Sentence = "\n" + Sentence
        with open(path, mode='a',encoding="utf-8") as f:
            f.writelines(Sentence)

    # 任意のパスにディレクトリまたはファイルをコピー
    def Copy(pathBefore, pathAfter):
        if "." in pathBefore:
            shutil.copy(pathBefore, pathAfter)
        else:
            shutil.copytree(pathBefore, pathAfter)

    # 任意のパスにディレクトリまたはファイルを移動
    def Move(pathBefore,pathAfter):
        shutil.move(pathBefore, pathAfter)

    # 任意のパスにディレクトリを作成
    def MakeDir(path):
        os.makedirs(path)

    # ディレクトリまたはファイルを削除
    def Remove(path):
        if "." in path:
            os.remove(path)
        else:
            shutil.rmtree(path)

    # ファイルの更新日時を変更
    def ChangeUpdateTime(path, timelist): # 西暦/月/日/時/分/秒 で入力
        time = Define.Date(timelist).timestamp()
        os.utime(path, (time, time))

class Program:
    # プログラムを強制終了
    def Exit():
        sys.exit()

class Define:
    # 入力からDatetimeオブジェクトを作成
    def Date(timelist):
        return datetime.datetime.strptime("/".join(map(str, timelist)), "%Y/%m/%d")

    def Time(timelist):
        return datetime.datetime.strptime("/".join(map(str, timelist)), "%H/%M/%S")

    def DateTime(timelist):
        return datetime.datetime.strptime("/".join(map(str, timelist)), "%Y/%m/%d/%H/%M/%S")
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