【6】Python 标准库基础

Python 标准库基础

一、实验介绍

1.1 实验内容

本节实验介绍python的标准库。

1.2 实验知识点

  • Python基本概念

1.3 实验环境

  • python2.7
  • Xfce终端

1.4 适合人群

本课程难度为初级,适合没有编程经验的初学者。

二、开发准备

启动Python

登录系统后输入python命令进入交互式操作模式

$ python

三、实验步骤

3.1 操作系统接口

简介

os 模块提供了很多与操作系统交互的函数:

>>> import os
>>> os.getcwd()      # Return the current working directory
'/home/shiyanlou'
>>> os.chdir('/tmp')   # Change current working directory
>>> os.system('mkdir today')   # Run the command mkdir in the system shell
0

应该用 import os 风格而非 from os import * 。这样可以保证随操作系统不同而有所变化的 os.open() 不会覆盖内置函数 open()

在使用一些像 os 这样的大型模块时内置的 dir() 和 help() 函数非常有用:

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

针对日常的文件和目录管理任务,shutil 模块提供了一个易于使用的高级接口:

>>> import shutil
>>> shutil.copyfile('Desktop/firefox.desktop', 'firefox2')
>>> shutil.move('firefox2', 'firefox3')

3.2 文件通配符

简介

glob 模块提供了一个函数用于从目录通配符搜索中生成文件列表:

>>> import glob, os
>>> os.chdir('Desktop')
>>> glob.glob('*.desktop')
['gvim.desktop', 'lxterminal.desktop', 'firefox.desktop']

3.3 命令行参数

简介

通用工具脚本经常调用命令行参数。这些命令行参数以链表形式存储于 sys 模块的 argv 变量。例如在命令行中执行 python demo.py one two three 后可以得到以下输出结果

>>> import sys
>>> print sys.argv
['demo.py', 'one', 'two', 'three']

getopt 模块使用 Unix getopt() 函处理 sys.argv 。更多的复杂命令行处理由 argparse 模块提供。

3.4 错误输出重定向和程序终止

简介

sys 还有 stdin , stdout 和 stderr 属性,即使在 stdout 被重定向时,后者也可以用于显示警告和错误信息

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

大多脚本的定向终止都使用 sys.exit() 。

3.5 字符串正则匹配

简介

re 模块为高级字符串处理提供了正则表达式工具。对于复杂的匹配和处理,正则表达式提供了简洁、优化的解决方案

>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值