25 Jul 2015
题目: 批量创建目录
我的解答
#!/usr/bin/python # Filename: exam01.py '''for auto create folder, and check results. ''' import os depts=['SALES','PURCHASE','ADMIN','PRODUCTION','ACCOUNT'] for dept in depts: delete=os.system('rm -rf /tmp/python/%s'%dept) result=os.popen('mkdir /tmp/python/%s'%dept) # 这里是错误的,因为result是一个文档目录,a为空 a=print(result) if dept in a: print '%s create success'%dept else: print '%s create failed'%dept
上面是不合适的方式,是shell的思维方式
老师的解答
# coding:utf-8 import os depts=["人事部","销售部","技术部"] for dept in depts: try: os.mkdir(dept) except OSError as e: print '文件【s%】创建失败,原因【s%】' %(dept,e.strerror)
不同点:
# coding:utf-8指定中文编码os.mkdir()函数,让函数和系统打交道而不是自己写shell命令try:+ except *** as *** 来截取尝试操作的异常输出PS:python多版本共存的问题,可使用virtualenv来解决
安装pip
wget https://bootstrap.pypa.io/get-pip.py python get-pip.py
- pip如果用get-pip.py的形式装,会根据python环境安装相应版本,如果需要安装固定版本的pip,可以源码安装。
- easy_install也是一个包管理器,不过更推荐pip
Wheels are the new standard of python distribution and are intended to replace eggs.
wheels是一个用来替代eggs的python发行版的新标准。
yum install python-virtualenv python-virtualenvwrapper pip install virtualenv virtualenv-wrapper yum install python-virtualenv
# Bpython pip install bpython # ipython pip install ipython
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!