Python常用代码段
发表于更新于
字数总计:648阅读时长:3分钟阅读量: 长沙
读取和写入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}
>>>OrderedDict(sorted(d.items(), key=lambda t: t[0])) OrderedDict([('apple',4), ('banana', 3), ('orange', 2), ('pear', 1)])
>>>OrderedDict(sorted(d.items(), key=lambda t: t[1])) OrderedDict([('pear',1), ('orange', 2), ('banana', 3), ('apple', 4)])
>>>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
random.random()
random.choice(one_list)
|