Python常用模块用法分析

2019-10-05 20:30:49于丽

os.getgruops() 得到用户组名称列表
os.getlogin() 得到用户登录名称
os.getenv 得到环境变量
os.putenv 设置环境变量
os.umask 设置umask
os.system(cmd) 利用系统调用,运行cmd命令

操作举例:

os.mkdir('/tmp/xx') os.system("echo 'hello' > /tmp/xx/a.txt") os.listdir('/tmp/xx')
os.rename('/tmp/xx/a.txt','/tmp/xx/b.txt') os.remove('/tmp/xx/b.txt') os.rmdir('/tmp/xx')

用python编写一个简单的shell

#!/usr/bin/python
import os, sys
cmd = sys.stdin.readline()
while cmd:
  os.system(cmd)
  cmd = sys.stdin.readline()

用os.path编写平台无关的程序

os.path.abspath("1.txt") == os.path.join(os.getcwd(), "1.txt")
os.path.split(os.getcwd()) 用于分开一个目录名称中的目录部分和文件名称部分。
os.path.join(os.getcwd(), os.pardir, 'a', 'a.doc') 全成路径名称.
os.pardir 表示当前平台下上一级目录的字符 ..
os.path.getctime("/root/1.txt")  返回1.txt的ctime(创建时间)时间戳
os.path.exists(os.getcwd()) 判断文件是否存在
os.path.expanduser('~/dir') 把~扩展成用户根目录
os.path.expandvars('$PATH') 扩展环境变量PATH
os.path.isfile(os.getcwd()) 判断是否是文件名,1是0否
os.path.isdir('c:Python26temp') 判断是否是目录,1是0否
os.path.islink('/home/huaying/111.sql') 是否是符号连接 windows下不可用
os.path.ismout(os.getcwd()) 是否是文件系统安装点 windows下不可用
os.path.samefile(os.getcwd(), '/home/huaying') 看看两个文件名是不是指的是同一个文件
os.path.walk('/home/huaying', test_fun, "a.c")

遍历/home/huaying下所有子目录包括本目录,对于每个目录都会调用函数test_fun.

例:在某个目录中,和他所有的子目录中查找名称是a.c的文件或目录:

def test_fun(filename, dirname, names): //filename即是walk中的a.c dirname是访问的目录名称
  if filename in names: //names是一个list,包含dirname目录下的所有内容
 print os.path.join(dirname, filename)
os.path.walk('/home/huaying', test_fun, "a.c")

文件操作

1.打开文件

f = open("filename", "r") r只读 w写 rw读写 rb读二进制 wb写二进制 w+写追加

2.读写文件

f.write("a") f.write(str) 写一字符串 f.writeline() f.readlines() 与下read类同
f.read() 全读出来 f.read(size) 表示从文件中读取size个字符
f.readline() 读一行,到文件结尾,返回空串. f.readlines() 读取全部,返回一个list. list每个元素表示一行,包含"n"
f.tell() 返回当前文件读取位置
f.seek(off, where) 定位文件读写位置. off表示偏移量,正数向文件尾移动,负数表示向开头移动。where为0表示从开始算起,1表示从当前位置算,2表示从结尾算.
f.flush() 刷新缓存

3.关闭文件