2008年6月24日 星期二

[Python] 字串處理, 檔案讀取, 系統參數, Trace目錄

Python 字串處理:

                                                                        return value
切token : str.split(delimiter) list
找字尾 : str.endswith(endString) bool (有沒有找到)
找字首: str.startswith(startString) bool (有沒有找到)
找子字串 : str.find(subString) 子字串的開頭位址
去空白 : str.strip() string

Regular expression:

re.search(regex, subject)
re.match(regex, subject)
re.findall(regex, subject)
re.finditer(regex, subject)
re.sub(regex, replacement, subject)
re.split(regex, subject)
re.complie(regex, subject)

檔案處理:

fp = open(file, "r") #讀檔
fileString = fp.read() #把整個檔案讀入buffer
fileLines = fp.readlines() #把整個檔案以一行一行形式讀入list

執行參數:

import sys

sys.argv #參數個數
sys.argv[1] #第1個參數


Trace 目錄:

import os, sys
from stat import *

def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''

for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname

def visitfile(file):
print 'visiting', file

if __name__ == '__main__':
walktree(sys.argv[1], visitfile)


參考資料:
Python's re Module
stat -- Interpreting stat() results
Common string operations
Python Library Reference

沒有留言: