#contents
----
***文字コードの変換 [#qdcb5f5f]
文字列のエンコーディングを変換するには次のようにすればよい。(2.4)
 str.encode("cp932")
 str.decode("euc-jp")
UTF-8の内部コードを直接ソースファイルに書くには
 u"あいうえお"
みたいに文字列の頭にuをつける。
 r"あいうえお"
みたいにrをつけるとraw文字列(?)というのになるらしい。文字列のバイトをそのままという意味か?

***ヘルプの引き方、モジュールのメンバの調べ方 [#l09c5a43]
-dir('''module''')~
モジュールのメンバー一覧
-help('''module''')~
モジュールのヘルプ

 help('modules') #利用可能なモジュールの一覧


***コマンドライン引数の処理 [#fcb66e18]
引数はsys.argvにリスト形式で入っている。またオプション引数の解析はgetoptが使える。~
 getopt(args, shortopts, longopts=[])
-shortopts は一文字。値をとる場合は:をつける(例 -v -n 10のような場合"vn:")
-longoptsは長いオプション名。省略可。値をとる場合は=をつける(例--help --width 10のような場合、["help", "width="])

getoptを使った引数の解析。
 import sys, getopt
 try:
     optlist, args = getopt.getopt(sys.argv[1:], "hs:", longopts=["help", "size="])
 except getopt.GetoptError:
     #エラー処理
     sys.exit(0)
 
 for opt, args in optlist:
     if opt in ("-h", "--help"):
         hogehoge
     if opt in ("-s", "--size"):
         fugofugo

***ファイルIO [#v4230c1a]
 f = file('file_name', mode)
 f = open('file_name', mode)
モード
-'r' 読み込み
-'w' 書き出し
-'a' 追加書き出し
-'b' バイナリ(不明)
-'ba' バイナリ読み込み
-'wa' バイナリ書き出し
-'br' バイナリ読み込み
-'bw' バイナリ書き出し

ファイルオブジェクトから一行ごとに取り出すには
 for line in fileobj:

***ファイル操作 [#aae4789f]
 os.tmpfile()           一時ファイルのファイルオブジェクトを返す
 os.chdir(path)         chdir
 os.getcwd()            pwd
 os.chmod(path,mode)    chmod
 os.listdir(path)       pathに含まれるファイルとディレクトリのリスト
 os.mkdir(path[,mode])  ディレクトリ作成
 os.mkdirs(path[,mode]) 再帰的なディレクトリ作成
 os.remove(path)        ファイル削除
 os.removeddirs(path)   再帰的なディレクトリ削除
 os.rename(src, dst)    改名
 os.renames(old, new)   再帰的にパスを削除&作成する
 os.rmdir(path)         ディレクトリ削除
 
 glob.glob("*.exe")     ワイルドカードによるファイルのリスト
 
 os.path.abspath(path)
 os.path.basename(path)
 os.path.dirname(path)
 os.path.exists(path)
 os.path.expanduser(path)       ~をユーザーのホームの置き換える
 os.path.expandvars(path)       環境変数を展開する$name, ${name}
 os.path.getatime(path)
 os.path.getttime(path)
 os.path.getctime(path)
 os.path.getsize(path)
 os.path.isabs(path)
 os.path.isfile(path)
 os.path.isdir(path)
 os.path.islink(path)
 os.path.ismount(path)
 os.path.join(path[,path...])   パスの結合
 os.path.normcase(path)
 os.path.normpath(path)
 os.path.realpath(path)
 os.path.samefile(path1, path2)
 os.path.sameopenfile(fp1, fp2)
 os.path.split(path)            headとtailに分解
 os.path.splitdrive(path)       drive, tailに分解
 os.path.splittext(path)         root, extのペア

-再帰的にファイルを収集(2.2以下の場合)
 import os
 def printFiles(arg, dir, files):
     for f in files:
         print os.path.join(dir, f)
 os.path.walk("C:\python24", printFiles, None)
-再帰的にファイルを収集(2.3以上の場合)
 import os
 for root, dirs, files in os.walk("C:\python24"):
     for fname in files:
         print os.path.join(root, fname)

----
[[CategoryPython]]


HTML convert time: 0.003 sec.