也不是经常使用 Python,每次用时都忘的差不多,又需要重新查资料。所以,开篇博客记录下这些琐碎的知识点。
都是入门基础级别的知识点,大神请出门左拐👋👋。
获取日期
Python lib doc: datetime
1 2 3 4 5 6 7 8 9
| import datetime
print datetime.datetime.now().strftime('%m-%d')
delta = datetime.timedelta(1) yestoday = datetime.datetime.now() - delta print yestoday.strftime('%m-%d')
|
列表(list)
1 2 3 4 5 6 7
| array = ['a', 'abc', 'd']
array = [item for item in array if item.startswith('a')]
array.extend(['e', 'f'])
|
文件IO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import os, shutil
os.mkdir('folder')
os.rmdir('empty_folder')
if os.path.exists('folder'): shutil.rmtree('folder')
os.rename("path/to/current/file.foo", "path/to/new/destination/for/file.foo")
for curdir, dirnames, filenames in os.walk('folder'): for filename in filenames: path = os.path.join(curdir, filename) print path
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| import json, codecs
with open('result.json', 'w') as file: json.dump(data, file, ensure_ascii=False, indent = 4)
with codecs.open('result.json', 'w', 'utf-8') as file: json.dump(data, file, ensure_ascii=False, indent = 4)
with open('gz020.json', 'r') as file: data = json.load(file)
|
正则表达式
1 2 3 4 5 6 7 8 9 10
| import re
re.findall(r'ing', 'string_input')
re.findall(r'<table class="olt">.*?</table>', string, flags=re.DOTALL+re.MULTILINE)
|
网络请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import urllib2
headers = { 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36', }
def sendReq(url, body, headers): try: req = urllib2.Request(url, body, headers) return urllib2.urlopen(req).read() except Exception, e: print e return None
response = sendReq('https://m.baidu.com/', '', headers) print response
|