ファイルの読み書き

open() / codecs.open()

ファイル操作は With を使え!

import codecs
 
with codecs.open('sample1.txt', 'r', 'utf8', 'ignore') as fr :
    with codecs.open('sample2.txt', 'w', 'ms932', 'ignore') as fw :
        for line in fr.readlines() :
            fw.write(line.replace('\r\n','とかいってみるテスト\r\n'))

めっちゃすっきりしたコードになる。With 節を抜けるときにファイルを閉じてくれる (エラー時にも閉じてくれる)
With を使わないと・・・

killyou.jpeg

ディレクトリとファイルの操作

os.path.join(tmp, tmp.txt)tmp/tmp.txtOS依存のパスセパレータで連結(\/)
os.path.dirname('tmp/tmp.txt')tmp
os.path.basename('tmp/tmp.txt')tmp.txt
os.path.abspath('tmp/tmp.txt')'/Users/atsushi/tmp/tmp.txt'カレントディレクトリと連結
os.path.split('tmp/tmp.txt')('tmp', 'tmp.txt')
os.path.exists('tmp/tmp.txt')True存在チェック
os.remove('tmp/tmp.txt')ファイル削除(dir削除は OSError)
os.mkdir('tmp/sub1/sub2')ディレクトリを作成(途中のディレクトリが無かったら OSError)
os.makedirs('tmp/sub1/sub2')再帰的にディレクトリを作成
os.rmdir('tmp')ディレクトリを削除(中身があったら OSError)
os.remvedirs('tmp')ディレクトリを再帰的に削除(ファイルがあったら OSError)
os.listdir('tmp')['sub1','tmp.txt']ディレクトリ配下のファイルのリスト
shutil.rmtree('tmp')ディレクトリを再帰的に削除(ファイルも消す)
shutil.rename(pre,post)リネーム(別パスへの移動にも使える)
shutil.copyfile(from,to)ファイルコピー
shutil.copy(from,to)ファイルコピー、toがディレクトリなら直下に同名でコピー
shutil.copy2(from,to)shutil.copy() + 属性情報もコピー

ファイル情報

>>> import os
>>> m = os.stat('pdfocrx.log')
>>> m
posix.stat_result(
st_mode=33188, 
st_ino=4444284, 
st_dev=16777218, 
st_nlink=1, 
st_uid=501, st_gid=20, 
st_size=1358, 
st_atime=1350489644, 
st_mtime=1348017627, 
st_ctime=1348017627)
>>> import time
>>> time.ctime(m.st_ctime)
'Wed Sep 19 10:20:27 2012'
 
[~]$ ls -la pdfocrx.log 
-rw-r--r--  1 atsushi  staff  1358  9 19 10:20 pdfocrx.log

Python


添付ファイル: filekillyou.jpeg 2161件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS   sitemap
Last-modified: 2012-11-04 (日) 23:19:17 (4183d)
Short-URL: https://at-sushi.com:443/pukiwiki/index.php?cmd=s&k=f94e60b18d
ISBN10
ISBN13
9784061426061