リンク
ちゃんと調べるときは
http://www.python.jp/doc/release/
Wiki内検索
最近更新したページ
最新コメント
文字コードの判定 by awesome things!
正規表現 by awesome things!
辞書 by stunning seo guys
文字列の16進変換 by check it out
文字コードの変換 by check this out
デバッガ by check this out
サブプロセス by watch for this
文字コードの判定 by watch for this
サニタイジング by check this out
タグ

ファイルシステム

ファイルの普通の読み書きはこっち

標準ドキュメントへの近道

おやくそく
import os

基本操作


パス、ファイルが存在するかどうか
os.path.exists(path_for_check)

ファイルのコピー
shutil.copy2(src_file, dst_dir)

ディレクトリ配下をまるごとコピー
shutil.copytree(src_dir, dst_dir)

ディレクトリの配下の一覧
os.listdir(targetdir)

ファイルの属性の取得


statから必要なものをインポート
from stat import ST_MODE, S_ISDIR, ST_CTIME

ファイルの作成時刻をとる
os.stat(filename)[ST_CTIME]

Windowsだとこんな感じ
os.stat(filename.encode('cp932'))[ST_CTIME]

ディレクトリのパス、配下にあるディレクトリ、ファイルをそれぞれタプルで返す。


>>> for path, dirs, files in os.walk('c:\\temp'):
...   print 'PATH: %s' % str(path)
...   for dir in dirs:
...     print 'DIR: %s' % str(dir)
...   for file in files:
...     print 'FILE: %s' % str(file)
...
PATH: c:\temp
DIR: dir1
DIR: dir2
FILE: file1.txt
FILE: file2.txt
PATH: c:\temp\dir1
FILE: file3.txt
PATH: c:\temp\dir2
DIR: dir3
FILE: file4.txt
PATH: c:\temp\dir2\dir3
FILE: file5.txt
>>>

タイムスタンプの変更


更新時刻とアクセス時刻はこれで変えられる

>>> 
>>> import os, time
>>> from stat import ST_ATIME, ST_MTIME
>>> 
>>> os.stat("a.txt")[ST_MTIME]
1211516317
>>> 
>>> time.localtime(1211516317)
(2008, 5, 23, 13, 18, 37, 4, 144, 0)
>>> 
>>> os.utime("a.txt", (1111111111, 1222222222))
>>> 
>>> time.localtime(os.stat("a.txt")[ST_ATIME])
(2005, 3, 18, 10, 58, 31, 4, 77, 0)
>>> 
>>> time.localtime(os.stat("a.txt")[ST_MTIME])
(2008, 9, 24, 11, 10, 22, 2, 268, 0)
>>> 
2008年07月24日(木) 16:14:41 Modified by hebi_




スマートフォン版で見る