Python常用代码段

读取和写入json文件

1
2
3
4
5
6
7
# 写
with open(json_path, 'w') as f:
json.dump(self.items, f)

# 读
with open(json_path) as f:
items = json.load(f)

读取和写入csv文件

1
2
3
4
5
6
7
8
9
10
11
# 读
with open(csv_file) as f:
csv_reader = csv.reader(f, delimiter=',')
for row in csv_reader:
print row

# 写
with open(csv_file, 'wb') as f:
csv_write = csv.writer(f)
for row in csv_data_list:
csv_write.writerow(row)

OrderedDict 排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> from collections import OrderedDict
>>> d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

#按key排序
>>>OrderedDict(sorted(d.items(), key=lambda t: t[0]))
OrderedDict([('apple',4), ('banana', 3), ('orange', 2), ('pear', 1)])

#按value排序
>>>OrderedDict(sorted(d.items(), key=lambda t: t[1]))
OrderedDict([('pear',1), ('orange', 2), ('banana', 3), ('apple', 4)])

#按key的长度排序
>>>OrderedDict(sorted(d.items(), key=lambda t: len(t[0])))
OrderedDict([('pear',1), ('apple', 4), ('orange', 2), ('banana', 3)])

打开和读取文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 如果文件内容只有一行,读和写
with open('/path/file.txt', 'r') as f:
f.read()

with open('/path/file.txt', 'w') as f:
f.write('Hello, World!')

# 如果文件是多行
with open('/path/file.txt') as f:
for line in f:
print line

with open('/path/file.txt', 'w') as p:
for each in file_list:
p.write(str(each) + '\n')

比较两个字符串之间的相似度

1
2
3
4
5
6
7
import difflib
a = '1111'
b = '11112'
seq = difflib.SequenceMatcher(None, a, b)
ratio = seq.ratio()
print ratio
>>> 0.88888888888

打开资源管理器

windows可以使用os模块

os.system("explorer.exe %s" % yourPath)

linux可使用subprocess

subprocess.Popen(["bash", "-l", "-c", "dolphin {}".format(yourPath)])

创建一个临时目录

1
2
import tempfile
temp_dir = tempfile.mkdtemp()

这样就可以得到一个临时的目录,我们可以获取这个目录的路径,并创建一个临时文件。

1
2
3
4
import os
temp_file = os.path.join(temp_dir, 'temp.txt')
with open(temp_file, "w") as file:
file.write("balabalabal....")

使用shutil复制,删除目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import shutil
import os

# 删除空目录
os.removedirs('dir_path')

# 删除非空目录
shutil.rmtree('dir_path')

# 复制目录(会递归复制目录内所有文件夹和文件)
shutil.copytree(a_folder, b_folder)

# 复制中忽略指定的文件类型
ignore_file = shutil.ignore_patterns("*.pyc", "*.~")
shutil.copytree(a_folder, b_folder, ignore=ignore_file)

将一个列表内的每个元素作为变量名

1
2
3
a_list = ['a', 'b', 'c', 'd', 'e']
for i in a_list:
locals()[i] = 'string name'

比较a和b的最大值

1
2
3
4
5
a = 5
b = 15
c = [b,a][a>b]
print c
>>> 15

随机获取数,抽取列表

1
2
3
4
5
6
7
import random

# 获取一个0.0 - 1.0的浮点数
random.random()

# 从列表随机抽出一个值
random.choice(one_list)