Tugqi Biz
  • Home
  • Categories
  • Tags
  • Archives

Python 代码片段

python logging¶

import logging  
logging.basicConfig(filename = os.path.join(os.getcwd(), 'log.txt'), level = logging.DEBUG)  
logging.debug('this is a message')  

python get line num¶

f = open("test.txt")
for i, l in enumerate(f):
    print i

python 脚本基本结构¶

import sys

source_file = sys.argv[1]

if __name__ == "__main__":
     my_func(source_file)

python file¶

f = open(file, "a") ## a meaning append
f = open(file, "w") ## w meaning write

python 正则¶

import re
pattern = re.compile("[a-zA-Z]")
result = pattern.search("adsfuhefdfkj435")
print result.group()

python 下载静态文件,如,mp3¶

import urllib
urllib.urlretrieve(audio_url, "name.mp3")

升级pip¶

easy_install -U pip

dir()¶

  • built-in function;
  • return a list of valid attributes for an object;
  • default: global objects

decode(), encode()¶

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。


  • « Shell 代码片段
  • Mysql 代码片段 »

Published

Mar 30, 2015

Category

IT

Tags

  • Python 15
  • Snippets 4
  • Powered by Pelican. Theme: Elegant by Talha Mansoor