3
2

More than 3 years have passed since last update.

PythonでWindowsのディレクトリで使用できない文字列を変換して作成する

Posted at

概要

Windowsでは下記の半角文字列が禁則文字であり、ディレクトリ作成時に使用できない。
¥ / : * ? ” < > |
半角文字列の場合は、全角文字に変換してディレクトリ作成を行うプログラムを下記に記載

前提条件

  • Windows 10
  • Python3.7

サンプルPG

  • プログラム概要
    • 正規表現を用いて禁則文字が存在する場合は全角変換する
create_dir.py
import os
import re

trans_tone = {
    u'\:': u':',
    u'\/': u'/',
    u'\¥': u'',
    u'\?': u'?',
    u'\"': u'”',
    u'\<': u'<',
    u'\>': u'>',
    u'\*': u'*',
    u'\|': u'|'
}

def main():

    dir_name = ":/\?<>*|"
    dir_name = multiple_replace(dir_name, trans_tone)

    os.makedirs(dir_name)


def multiple_replace(text, adict):
    """ 一度に複数のパターンを置換する関数
    - text中からディクショナリのキーに合致する文字列を探し、対応の値で置換して返す
    - キーでは、正規表現を置換前文字列とできる
    """

    rx = re.compile('|'.join(adict))

    def dedictkey(text):
        """ マッチした文字列の元であるkeyを返す
        """
        for key in adict.keys():
            print(key)
            if re.search(key, text):
                return key

    def one_xlat(match):
        return adict[dedictkey(match.group(0))]

    return rx.sub(one_xlat, text)


if __name__ == "__main__":
    main()

参考ページ

3
2
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
3
2