| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Python サンプルコード

提供: MyMemoWiki
2020年9月14日 (月) 15:17時点におけるPiroto (トーク | 投稿記録)による版 (→‎ファイルの内容を表示)
ナビゲーションに移動 検索に移動

Python サンプルコード

Python 2.5 | 言語まとめ Python | Python 標準ライブラリ概観 |

ライブラリ

ライブラリ・フレームワーク 内容
Django Webアプリケーションフレームワーク
Google App Engine Google Webアプリケーションフレームワーク
Python Imaging Library イメージング
Beautiful Soup HTML解析
Python Win32 Extensions COM操作
pyExcelerator Excel操作

はじめに

HELP

ビルトインを調べる

  1. >>> help(__builtins__)
  2. >>> dir(__builtins__)

属性の確認

  • "オブジェクト"に調べたいオブジェクトを設定
  1. >>> dir(オブジェクト)

ヘッダー

  1. #!python2.5
  2. # -*- coding: utf-8 -*-

オブジェクト

オブジェクトの型

API 概要
type() 【組み込み関数】オブジェクトの型を返す
  1. import os
  2. print 'os type:%s' %(type(os))
  3. fils = os.listdir('c:\work')
  4. print 'os.listdir type:%s' %(type(fils))
  5. print 'listdir[0] type:%s' %(type(fils[0]))
  6.  
結果
  1. os type:<type 'module'>
  2. os.listdir type:<type 'list'>
  3. listdir[0] type:<type 'str'>

ディレクトリとファイル

ディレクトリを再帰しながらファイルをリスト

  1. def check_dir(dir):
  2. for o in glob.glob(os.path.join(dir,"*")):
  3. if os.path.isdir(o):
  4. check_package(o)
  5. else:
  6. print o

ディレクトリの内容を表示

API 概要
os.listdir ディレクトリ内容のリストを取得
  1. import os
  2. fs = os.listdir('c:\work')
  3. for f in fs:
  4. print f
  5.  

ディレクトリの内容を表示(2)

API 概要
os.path.isdir パスのディレクトリ判定
os.path.exists パスの存在判定
print 'C言語スタイルの書式文字' %(パラメータ) 書式付出力
  1. import os
  2. basedir = 'c:\work'
  3. fils = os.listdir(basedir)
  4. print 'dir\texists\tpath'
  5. print '------------------'
  6. for fi in fils :
  7. p = basedir + os.sep + fi
  8. print '%s\t%s\t%s' %(str(os.path.isdir(p)), str(os.path.exists(p)), p)
  9.  

Python 文字コードを指定してファイルを開く

ファイルの内容を表示

  • ディレクトリに含まれるファイルの内容を出力
API 概要
os.chdir カレントディレクトリの変更
os.path.abspath 絶対パスの取得
open 【組み込み関数】ファイルを開く

<blockquote>print の末尾に "," で、改行出力を抑制</blockquote>

  1. import os
  2. os.chdir('c:\work')
  3. fils = os.listdir('.')
  4. for fi in fils:
  5. p = os.path.abspath(fi)
  6. if not os.path.isdir(p) :
  7. print '===== %s =====' %(fi)
  8. f = open(p)
  9. try:
  10. for line in f:
  11. print line,
  12. finally:
  13. f.close()

ファイルをwithで開く

  1. with open('./out/page_index.txt', 'w') as f:
  2. f.write('hoge')

ファイルの情報を取得

API 概要
os.stat 与えられたパスにstatシステムコールを実行
time.ctime エポックタイムからの秒数をローカル時間に変換
  1. >>> import time
  2. >>> import os
  3. >>> r = os.stat(r'/test.txt')
  4. >>> r
  5. nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=4508L, st_atime=1266996480L, st_mtime=1266452528L, st_ctime=1251076742L)
  6. >>> ct = time.ctime(r.st_ctime)
  7. >>> ct
  8. 'Mon Aug 24 10:19:02 2009'

絶対パスからファイル名のみを取得

  • os.path.basename
  1. >>> import os
  2. >>> os.path.basename('c/work/test.txt')
  3. 'test.txt'

パスを生成

API 概要
os.path.join 2つ以上のパスを結合する。必要なら\を挿入
  1. join(a, *p)
  1. >>> import os
  2. >>> p = os.path.join('c:\\', 'work', 'test')
  3. >>> print p
  4. c:\work\test

ディレクトリ判定

API 概要
os.path.isdir(path) ディレクトリか否かを判定
  1. >>> import os
  2. >>> os.path.isdir('c:\work')
  3. True

ディレクトリの走査(再帰)

例1
  1. import os
  2. import pprint
  3.  
  4. def trav(path, fn=):
  5. l = []
  6. l.append(fn)
  7. d = os.path.join(path,fn)
  8. if os.path.isdir(d):
  9. for f in os.listdir(d):
  10. l.append(trav(d,f))
  11. return l
  12.  
  13. l = trav('C:\\', 'Python25')
  14. pprint.pprint(l)
例2
  1. # -*- coding: utf-8 -*-
  2. import os
  3.  
  4. class FileTrav(object):
  5. def traverse(self, working_dir, depth=0):
  6. path = os.path.abspath(working_dir)
  7. for f in os.listdir(path):
  8. fl = os.path.join(path, f)
  9. print '%s%s' % ('\t' * depth, fl)
  10. if os.path.isdir(fl):
  11. self.traverse(working_dir=fl, depth=depth + 1)
  12.  
  13. if __name__ == '__main__':
  14. tp = FileTrav()
  15. tp.traverse(working_dir=os.getcwd())

オブジェクト指向

コレクション

リスト

結合

  1. >>> l = []
  2. >>> l.append('a')
  3. >>> l.append('b')
  4. >>> l
  5. ['a', 'b']
  6. >>> ','.join(l)
  7. 'a,b'

<blockquote>リスト同士を結合する場合、extend を利用する</blockquote>

スライス

API 概要
list() リストの生成、[リストの内容,・・・]で宣言と同時に初期化
[開始位置:終了位置:STEP] スライス。開始位置から終了位置までSTEPごとに切り出す
  1. #l = list()
  2. l = [6,5,2,3,1,4]
  3. l.append(7)
  4. l.append(8)
  5. l.sort()
  6. print l
  7. print l[::2]
  8. print l[1::2]
結果
  1. [1, 2, 3, 4, 5, 6, 7, 8]
  2. [1, 3, 5, 7]
  3. [2, 4, 6, 8]

コンテナオブジェクトからリストを作成

  • 文字列は文字のコンテナオブジェクト
  1. msg = 'this is message.'
  2. l = list(msg)
  3. print l
結果
  1. ['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'm', 'e', 's', 's', 'a', 'g', 'e', '.']

タプル

  • リストや配列と異なり、用途や型が異なるオブジェクトをひとつにまとめるために使われる
  • C言語の構造体を匿名にしたようなものと考えることができる
  • ひとつの「かたまり」として変数に代入できる
  • 関数の返り値として使うこともできる。これによって、複数の値を返す関数を実現することができる
  • リストと同様に、個々の要素を添え字によって参照できる
  • あくまで「ひとつの値」であるため、一度構築したら中の値を変更することができない
  1. t1 = 1,'one',
  2. t2 = 2,'two',
  3. t3 = 3,'tree',
  4.  
  5. t = t1,t2,t3,
  6. print t
結果
  1. ((1, 'one'), (2, 'two'), (3, 'tree'))

Set

作成

  1. s = set('aaaabbbbccccddd')
  2. print s

操作

追加
  1. s.add('123')
共通集合
  1. s & set([1,2,3])
その他
  • union:和集合を返す
  • intersection:共通集合を返す
  • difference:差集合を返す
  • symmetric_difference:対称的差集合を返す
  • add:追加
  • remove:削除
結果
  1. set(['a', 'c', 'b', 'd'])

辞書

キーとそれに対応する値を同時に取り出す

  • iteritems() メソッドを使う
  1. >>> m = {'a':1,'b':2,'c':1,'d':2}
  2. >>> for k, v in m.iteritems():
  3. ... print '%s,%s' % (k, v)
  4. ...
  5. a,1
  6. c,1
  7. b,2
  8. d,2

条件にあった要素をリスト内包表記で取り出す

  1. >>> m = {'a':1,'b':2,'c':1,'d':2}
  2. >>> m2 = dict([(k, v) for k, v in m.iteritems() if v == 1])
  3. >>> m2
  4. {'a': 1, 'c': 1}

辞書に辞書を追加する

  1. >>> m = {'a':1,'b':2}
  2. >>> m1 = {'c':3,'d':4}
  3. >>> m.update(m1)
  4. >>> m
  5. {'a': 1, 'c': 3, 'b': 2, 'd': 4}

データベース

データベース(SQLite)の使用

  1. #!python2.5
  2. # -*- coding: utf-8 -*-
  3. import sqlite3
  4.  
  5. con = sqlite3.connect('/work/py/test.db')
  6.  
  7. #create database in RAM
  8. #con = sqlite3.connect(':memory:')
  9.  
  10. con.execute("create table test (id text, value text, note text)")
  11.  
  12. con.execute("insert into test values('1','aaa','01')")
  13. con.execute("insert into test values('2','bbb','02')")
  14. con.execute("insert into test values('3','ccc','01')")
  15.  
  16. con.commit()
  17.  
  18. p = ('01',)
  19. c = con.cursor()
  20. c.execute("select * from test where note=?", p)
  21.  
  22. for r in c:
  23. print r
  24.  
  25. con.close()
結果
  1. (u'1', u'aaa', u'01')
  2. (u'3', u'ccc', u'01')