Python小技巧
字符串分割:
方法一:列表综合,适用任意长度序列
[s[i:i+4] for i in range(0, len(seq), 4)]
方法二:re 模块,适用字符串,总长度要求是片段长度的整数倍
re.compile(r&'.{4}').findall(s)
方法三:struct 模块,适用字符串,总长度要求是片段长度的整数倍
struct.unpack(&'4s'*len(s)/4, s)
文件夹拷贝:
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import shutil
__doc__ = ''' copy all files from directory to an destination ,
It recreate directory tree of src to dst and replace or create
file in this directory.
If you have tree like this
src/A/dir/file
src/B/dir/sdir/file2
src/B/dir/file
and
then after script src dst
dst/dir/file
dst/dir/sdir/file2 -> this is the B file2 wich is taken
http://code.activestate.com/recipes/577493-recurse-copy-file/
'''
def copytree(src, dst):
if os.path.isdir(src):
if not os.path.exists(dst):
os.makedirs(dst)
for name in os.listdir(src):
copytree(os.path.join(src, name),
os.path.join(dst, name))
else:
shutil.copyfile(src, dst)
def main(dsrc, ddst):
for dirname in os.listdir(dsrc):
tocopy = os.path.join(dsrc, dirname)
for d in os.listdir(tocopy):
src = os.path.join(tocopy,d)
dst = os.path.join(ddst,d)
if os.path.isdir(src):
copytree(src, dst)
if __name__ == '__main__':
src = sys.argv[1]
dst = sys.argv[2]
main(src, dst)
多行字符串:
>>> t = ('hello'
... ' '
... 'world')
>>> t
'hello world'