[[diary/Kojima]]
・tilde-convert.py
波ダッシュ(Full Width Tilde)がうまく表示できないソフトがある問題、とりあえず原因は判明したので、
指定したディレクトリ以下にある 8f a2 b7 な波ダッシュなファイル、ディレクトリ名を a1 c1 に変換して
rename するようなスクリプトを書いてみた。
厳密に言うと UTF-8 界で "~" になるコードを "〜" に変換しているので、
ファイル名中に "~" があっても ”〜" にしてしまうので、そういうファイル名を使っている場合は要注意。
まぁ、手元ではそういうファイル名は作らないし、そうなってしまっているのを直したい意図もあるので、
俺様仕様 :-)
# とりあえず emacs のバックアップファイルはイジらないようにはしておいた
#! /usr/bin/python
# -*- coding: euc-jp -*-;
import getopt, sys, commands, os, struct
def conv_tilda(s):
if s.endswith("~") : # emacs のバックアップファイルは除く
return s
utf8 = s.decode('euc-jp')
conv = utf8.replace("~", u'〜')
euc = conv.encode('euc-jp')
return euc
def usage():
print sys.argv[0], " [-d] [-h] directory"
print "convert 8f a2 b7 wave-dash in file and directory name to a1 c1 wave-dash"
print " -d : dry run mode"
print " -h : print usage(this message)"
def get_parms():
try:
opts, args = getopt.getopt(sys.argv[1:], "hd", ["help", "dry-run"])
except getopt.GetoptError:
usage()
sys.exit(2)
result = [opts, args]
return result
def main():
opts, filelist = get_parms()
dry_run = False
for o, a in opts:
print "o:",o
if o in ("-d", "--dry-run"):
dry_run = True
if o in ("-h", "--help"):
usage()
sys.exit(2)
start_dir = filelist[0]
if os.access(start_dir,os.W_OK) == False:
if os.access(start_dir, os.F_OK) == False:
print start_dir, " cannot exist."
elif os.access(start_dir, os.R_OK) == False:
print start_dir, " cannot read."
else:
print start_dir, " is not writable."
sys.exit(2)
print "start_dir:", start_dir
list = os.walk(start_dir)
for root, dir, files in list:
for t in files:
tt = conv_tilda(t)
if t != tt:
old_name = os.path.join(root,t)
new_name = os.path.join(root, tt)
if dry_run == False:
print "file ", t , "should be", tt
os.rename(old_name, new_name)
else:
print "file ", t , "should be", tt
print "os.rename(", old_name , ",", new_name, ")"
list = os.walk(start_dir)
for root, dir, files in list:
for t in dir:
tt = conv_tilda(t)
if t != tt:
old_name = os.path.join(root,t)
new_name = os.path.join(root, tt)
if dry_run == False:
print "directory ", t , "should be", tt
os.rename(old_name, new_name)
else:
print "directory ", t , "should be", tt
print "os.rename(", old_name , ",", new_name, ")"
if ( __name__ == "__main__" ):
main()
Pythonだとシェルスクリプトみたいに" " や "*" 等の特殊文字をエスケープしないでもよさげなので、
こういう用途には案外便利だな。
#comment