python使用技巧(一)

来源:互联网 发布:ajax 返回json 解析 编辑:程序博客网 时间:2024/06/10 21:50

四:python使用技巧

1.       模式匹配

sTime = "\d{2}:\d{2}:\d{2}.\d{3}.\d{3}"

p = re.compile(sTime)

match = p.search(str_temp)

task_time = 0

if match:

        task_time = match.group()

2.       目录遍历

files = os.listdir(self.logpath)

for file in files:

#使用正则表达式匹配

p = re.compile(self.logname)

match = p.match(file)

if match:

        name = self.logpath + os.sep + file

        self.filename.append(name)

3.       系统目录分割符

Windows:  os.sep = ‘\’

Linux:     os.sep = ‘/’

4.       格式化输出

(1)       格式化输出到文件

%ns,设置输出内容的宽度,默认右对齐。

file.write("%s %10s %8s %10d  S[%16s %8s] W[%16s %8s] R[%16s %8s]\n"%(……)

(2)       格式化输出到控制台

print "%s %s %10s %6s %10d  S[%16s %8s] W[%16s %8s] R[%16s %8s]\n"%(……)

原创粉丝点击