这里主要收集一些关于python的常用用法,因为自己很容易忘,所有把它们整理起来放在一起。

如何存储与读取json文件

import json
data = {'a':123, 'b':789}
# **存储json文件**
with open('D:/test.json', 'w') as f:
  json.dump(data, f)
# 读取json文件
with open('D:/test.json', 'r') as f:
  load_json = json.load(f)
  print load_json

如何去列表重复

method 1:

a_list = ["aaa", "bbb", "ccc", "ccc", "ddd", "aaa", "eee"]
b_list = [n for i, n in enumerate(a_list) if n not in a_list[:i]]
print b_list
>>> ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

method 2:

a_list = ["aaa", "bbb", "ccc", "ccc", "ddd", "aaa", "eee"]
c_list = list(set(a_list))
print c_list
>>> ['eee', 'aaa', 'bbb', 'ccc', 'ddd'

比较a和b的最大值

a = 5
b = 15
c = [b,a][a>b]
print c
>>> 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')

比较两个字符串的相似度

import difflib
a = '1111'
b = '11112'
seq = difflib.SequenceMatcher(None, a, b)
ratio = seq.ratio()
print ratio
>>> 0.88888888888

过滤出列表里所有的字符串

a_list = [1,2,3,4,5,6,7,8,'test','text']
a_list = [x for x in a_list if type(x) == str]
print a_list
>>> ['test', 'text']

打开资源管理器

windows可以使用os模块

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

linux可使用subprocess

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

创建一个临时目录

import tempfile
temp_dir = tempfile.mkdtemp()

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

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

使用shutil复制,删除目录

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)

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

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

使用切片获取列表的奇数位和偶数位集合

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odds = a[::2]
evens = a[1::2]
print odds
print evens
>>>
[1, 3, 5, 7, 9]
[2, 4, 6, 8]

(待续)


From zero to hero