Tips
读写操作
- 使用codecs模块
import codecs
fp1 = codecs.open(filename,'w')
fp2 = codecs.open(filename, 'r', 'utf-8')
lines = fp2.readlins()
- 文件关闭
try:
f = open('/path/to/file', 'r')
print f.read()
finally:
if f:
f.close()
更简洁的表达:
with open('/path/to/file', 'r') as f:
print f.read()
read()
&readline()
&readlines()
read()
一次性读取文件的全部内容,read(size)
每次最多读取size个字节的内容readline()
可以每次读取一行内容readlines()
一次读取所有内容并按行返回list
总结
import codecs with codecs.open('/Users/michael/gbk.txt', 'r', 'gbk') as f: f.read()
文件操作
- shutil.copytree(windowsDir, photoDir)
工作目录
import os
curDir = os.getcwd() #获取当前工作目录
chDir = os.chdir(path) # 更改工作目录
defaultdict & dict = {}
dict = defaultdict(default_factory)
就是一个字典,只不过python自动为其键值赋上初值
>>> s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
>>> d = defaultdict(list)
>>> for k, v in s:
... d[k].append(v)
...
>>> d.items()
[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]
>>> s = 'mississippi'
>>> d = defaultdict(int)
>>> for k in s:
... d[k] += 1
...
>>> d.items()
[('i', 4), ('p', 2), ('s', 4), ('m', 1)]
list
[word for word in wordlist if word != '*']
# 生成列表for i,e in enumerate(list):
# 取出列表元素以及所在位置
下划线的使用
- object # public
- __object__ # special, python system use, user should not define like it
- __object # private (name mangling during runtime)
_object # obey python coding convention, consider it as private
单下划线开始的成员变量叫做保护变量,意思是只有类对象和子类对象自己能访问到这些变量
- 双下划线开始的是私有成员,意思是只有类对象自己能访问,连子类对象也不能访问到这个数据。
- 以单下划线开头
_foo
的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用from xxx import *
而导入 - 以双下划线开头的
__foo
代表类的私有成员 - 以双下划线开头和结尾的
__foo__
代表python里特殊方法专用的标识,如__init__()
代表类的构造函数。
内存释放
先del,再显式调用gc.collect()
import gc
del list
gc.collect()