python os模块system_Python 学习笔记 (7)—— OS模块

os 模块,正如其名,主要与操作系统打交道的,下面介绍下一些常见的功能

一、文件与目录操作

1、os.getcwd() 获取当前路径

>>> import os

>>> os.getcwd()

'/tmp/python'

2、os.listdir() 列出目录中的内容>>> import os

>>> os.listdir(os.getcwd())

['esc.py', '7.py', 'cat1.py', 'say.pyc', '2.py', 'backup_ver1.py', '5.py', '8.py', 'count.py', '3.py', 'replace.py', 'p_w_picpath']

注意,通过这个方法只能以列表的形式列出所有文件,但不能遍历该目录下的子目录

3、os.mkdir() 创建目录>>> import os

>>> os.mkdir('/tmp/testdir')

[root@node1 python]# ls /tmp/testdir/ -d

/tmp/testdir/

通过os.mkdir 只能创建一级目录,如果父目录不存在,则会报错:

>>> import os

>>> os.mkdir('/testdir/dirs')

Traceback (most recent call last):

File "", line 1, in

OSError: [Errno 2] No such file or directory: '/testdir/dirs'

一次性创建嵌套目录可使用os.makedirs,makedirs可以生成多层递归目录,removedirs可以删除多层递归的空目录,若目录中有文件则无法删除

>>> import os

>>> os.makedirs('/testdir/dirs')

>>> os.system('ls -ld /testdir/dirs')

drwxr-xr-x. 2 root root 4096 Dec 3 20:52 /testdir/dirs

0

4、os.rmdir() 删除目录>>> import os

>>> os.rmdir('/testdir/dirs')

>>> os.system('ls -l /testdir/dirs')

ls: cannot access /testdir/dirs: No such file or directory

512

目录必须为空,否则会报错

[root@node1 tmp]# mkdir testdir

[root@node1 tmp]# touch testdir/a

>>> import os

>>> os.rmdir('/tmp/testdir')

Traceback (most recent call last):

File "", line 1, in

OSError: [Errno 39] Directory not empty: '/tmp/testdir'

如果要删除可以借助os.system() 执行shell命令强行删除

>>> import os

>>> os.system('rm -rf /tmp/testdir')

0

>>> os.system('ls -l /tmp/testdir')

ls: cannot access /tmp/testdir: No such file or directory

512

5、os.chdir() 改变目录>>> import os

>>> os.getcwd()

'/tmp/python'

>>> os.chdir('/etc')

>>> os.getcwd()

'/etc'

6、os.remove() 删除文件>>> import os

>>> os.remove('/tmp/python/1.py')

7、os.rename(原文件名,改变文件名) 重命名文件或目录>>> import os

>>> os.rename('/tmp/test.txt','/tmp/python.txt')

>>> os.system('ls -l /tmp/*.txt')

-rw-r--r--. 1 root root 47 Dec 2 06:16 /tmp/myhello.txt

-rw-r--r--. 1 root root 82 Dec 2 06:18 /tmp/python.txt

0

os.renames() 递归的给目录重命名

>>> import os

>>> os.rename('/tmp/test/subdir','/tmp/test1/subdir1')

Traceback (most recent call last):

File "", line 1, in

OSError: [Errno 2] No such file or directory

>>> os.renames('/tmp/test/subdir','/tmp/test1/subdir1')

>>> os.system('ls -ld /tmp/test1/subdir1')

drwxr-xr-x. 2 root root 4096 Dec 4 20:06 /tmp/test1/subdir1

0

8、os.system() 执行shell 命令>>> import os

>>> os.system('ls /tmp')

backup myhello.txt python python.txt test yum.log

0

9、os 模块属性>>> os.curdir #当前工作目录的字符串名称

'.'

>>> os.pardir #(当前工作目录的)父目录字符串名称

'..'

>>> os.linesep #用于在文件中分隔行的字符串

'\n'

>>> os.sep #用来分隔文件路径名的字符串

'/'

>>> os.pathsep #用于分隔文件路径的字符串

':'

这个属性在写脚本的时候比较有用,比如在写备份脚本的时候,指定存放备份的路径可以这样:

>>> import time

>>> filename = time.strftime('%H%M%S')

>>> target_dir = '/tmp/backup'

>>> dirname = target_dir + time.strftime('%Y%m%d')

>>> target = dirname + os.sep + filename + '.tar.gz'

10、os.stat() 返回文件的属性>>> import os

>>> os.stat('/tmp/python.txt')

posix.stat_result(st_mode=33188, st_ino=924858, st_dev=64768L, st_nlink=1, st_uid=0, st_gid=0,

st_size=82, st_atime=1385936299, st_mtime=1385936293, st_ctime=1386076480)

可以通过字典遍历

#!/usr/bin/python

import os

import stat

import time

fileStats = os.stat('/tmp/python.txt')

fileInfo = {

'Size':fileStats[stat.ST_SIZE],

'LastModified':time.ctime(fileStats[stat.ST_MTIME]),

'LastAccessed':time.ctime(fileStats[stat.ST_ATIME]),

'CreationTime':time.ctime(fileStats[stat.ST_CTIME]),

'Mode':fileStats[stat.ST_MODE]

}

for infoField,infoValue in fileInfo.iteritems():

print infoField, ':' ,infoValue

[root@node1 python]# python stat.py

LastModified : Mon Dec 2 06:18:13 2013

Mode : 33188

CreationTime : Tue Dec 3 21:14:40 2013

LastAccessed : Mon Dec 2 06:18:19 2013

Size : 82

11、os.walk() 遍历目录函数声明:walk(top,topdown=True,οnerrοr=None)

1>参数top表示需要遍历的目录树的路径

2>参数topdown的默认值是"True",表示首先返回目录树下的文件,然后在遍历目录树的子目录.Topdown的值为"False"时,则表示先遍历目录树的子目录,返回子目录下的文件,最后返回根目录下的文件

3>参数onerror的默认值是"None",表示忽略文件遍历时产生的错误.如果不为空,则提供一个自定义函数提示错误信息后继续遍历或抛出异常中止遍历

4>该函数返回一个元组,该元组有3个元素,这3个元素分别表示每次遍历的路径名,目录列表和文件列表

#!/usr/bin/python

import os

def visitDir(path):

for root,dirs,files in os.walk(path):

for filespath in files:

print os.path.join(root,filespath)

if __name__ == "__main__":

path = "/root"

visitDir(path)

[root@node1 python]# python walk.py

/root/.bash_history

/root/install.log.syslog

/root/.bash_profile

/root/.viminfo

/root/anaconda-ks.cfg

/root/.bash_logout

/root/init.sh

/root/.cshrc

/root/.bashrc

/root/.tcshrc

/root/.lesshst

/root/install.log

/root/webproject/manage.py

/root/webproject/webproject/wsgi.pyc

/root/webproject/webproject/wsgi.py

/root/webproject/webproject/settings.pyc

/root/webproject/webproject/settings.py

12、获取系统信息>>> import os

>>> os.uname() #获取当前系统信息

('Linux', 'node1', '2.6.32-279.el6.x86_64', '#1 SMP Wed Jun 13 18:24:36 EDT 2012', 'x86_64')

>>> os.getuid() #获取当前用户ID

0

>>> os.getgid() #获取当前组ID

0

>>> os.getpid() #获取当前进程ID

1239

>>> os.getpgrp() #获取当前进程组ID

1239

>>> os.ctermid() #获取当前使用终端

'/dev/tty'

>>> os.getlogin() #获取当前登录的用户名

'root'

二、权限

13、os.access(路径,uid/gid)测试指定uid/gid 对指定目录有没有权限,有权限返回True,无权限返回False

>>> import os

>>> os.access('/tmp/test')

>>> os.access('/tmp/test',0)

True

>>> os.access('/tmp/test',33)

False

14、os.chmod(路径,权限) 修改文件/目录 权限>>> import os

>>> os.chmod ('/tmp/python.txt',0775)

>>> os.system('ls -l /tmp/python.txt')

-rwxrwxr-x. 1 root root 82 Dec 2 06:18 /tmp/python.txt

0

15、os.chown(路径,UID,GID) 修改拥有者,属组>>> import os

>>> os.chown('/tmp/python.txt',500,500)

>>> os.system('ls -l /tmp/python.txt')

-rwxrwxr-x. 1 python python 82 Dec 2 06:18 /tmp/python.txt

0

三、os.path 模块

16、os.path.basename() 去掉目录路径, 返回文件名>>> import os.path

>>> os.path.basename('/tmp/python.txt')

'python.txt'

17、os.path.dirname() 去掉文件名, 返回目录路径>>> import os.path

>>> os.path.dirname('/tmp/python.txt')

'/tmp'

18、os.path.join() 将分离的各部分组合成一个路径名>>> import os.path

>>> dir = '/tmp'

>>> file = 'python.txt'

>>> os.path.join(dir,file)

'/tmp/python.txt'

19、

os.path.getatime() 返回最近访问时间

os.path.getctime() 返回文件创建时间

os.path.getmtime() 返回最近文件修改时间

>>> import os.path

>>> os.path.getatime('/tmp/python.txt')

1385936299.3662264

>>> os.path.getctime('/tmp/python.txt')

1386107618.3203411

>>> os.path.getmtime('/tmp/python.txt')

1385936293.4863505

但这样看到的时间,是计算当前时间距离1970年1月1日的秒数的,不人性化,可以这样显示

>>> import os.path

>>> import time

>>> time.ctime(os.path.getatime('/tmp/python.txt'))

'Mon Dec 2 06:18:19 2013'

>>> time.ctime(os.path.getctime('/tmp/python.txt'))

'Wed Dec 4 05:53:38 2013'

>>> time.ctime(os.path.getmtime('/tmp/python.txt'))

'Mon Dec 2 06:18:13 2013'

20、os.path.getsize() 返回文件大小(以字节为单位)>>> import os.path

>>> os.path.getsize('/tmp/python.txt')

82

21、os.path.exists() 指定路径(文件或目录)是否存在>>> import os.path

>>> os.path.exists('/tmp/python.txt')

True

>>> os.path.exists('/tmp/python')

False

22、

os.path.isdir() 指定路径是否存在且为一个目录

os.path.isfile() 指定路径是否存在且为一个文件

>>> import os.path

>>> os.path.isdir('/tmp/python.txt')

False

>>> os.path.isdir('/tmp/')

True

>>> os.path.isfile('/tmp')

False

>>> os.path.isfile('/tmp/python.txt')

True

os.path.exists() 判断指定路径是否存在

>>> import os.path

>>> os.path.exists('/tmp/')

True

>>> os.path.exists('/tmpp/')

False

23、os.path.splitext() 分隔文件名和后缀名>>> import os.path

>>> os.path.splitext('python.txt')

('python', '.txt')

========================

其他 os 模块函数

文件处理mkfifo()/mknod() 创建命名管道/创建文件系统节点

remove()/unlink() 删除文件 os.remove()函数用来删除一个文件。

symlink() 创建符号链接

utime() 更新时间戳

tmpfile() 创建并打开('w+b')一个新的临时文件

目录/文件夹chroot() 改变当前进程的根目录

getcwdu() 返回当前工作目录并返回一个 Unicode 对象 os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。

makedirs() 创建目录/创建多层目录

removedirs() 删除多层目录

文件描述符操作open() 底层的操作系统 open (对于文件, 使用标准的内建 open() 函数)

read()/write() 根据文件描述符读取/写入数据

dup()/dup2() 复制文件描述符号/功能相同, 但是是复制到另一个文件描述符

设备号makedev() 从 major 和 minor 设备号创建一个原始设备号

major()/minor() 从原始设备号获得 major/minor 设备号

系统操作os.name 字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。

os.getenv() 获取一个环境变量,如果没有返回none

os.putenv(key, value) 设置一个环境变量值

分隔符os.sep() 文件夹分隔符,windows中是 /

os.extsep() 扩展名分隔符,windows中是 .

os.pathsep() 目录分隔符,windows中是 ;

os.linesep() 换行分隔符,windows中是 /r/n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值