0%

Python 学习笔记

也不是经常使用 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')]

# 合并list
array.extend(['e', 'f'])

文件IO

  • 文件夹操作 Sample
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
  • JSON存取 Sample
1
2
3
4
5
6
7
8
9
10
11
12
13
import json, codecs

# JSON存盘
with open('result.json', 'w') as file:
json.dump(data, file, ensure_ascii=False, indent = 4)

# 指定 ensure_ascii=False 和文件编码为utf-8,解决json中包含中文无法写入的问题
with codecs.open('result.json', 'w', 'utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent = 4)

# JSON读取
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')

# 多行匹配
# 1. 必须使用非贪婪模式
# 2. flags需要带上 re.DOTALL 和 re.MULTILINE
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