python基础课程_学习笔记20:标准库:有些收藏夹——os

标准库:有些收藏夹

os

os模块为您提供访问多个操作系统服务特征。

os和它的子模块os.path还包含一些用于检查、构造、删除文件夹和文件的函数,以及一些处理路径的函数。

os模块中一些重要函数和变量

函数/变量

描写叙述

environ

对环境变量进行映射

system(command)

在子shell中运行操作系统命令

sep

路径中的分隔符

pathsep

分隔路径的分隔符

linesep

行分隔符(‘ ’,’ ’,’ ’)

urandom(n)

返回n字节的加密强随机数据

os.environ映射包括前面讲述过的环境变量。如要訪问系统变量PYTHONPATH,能够使用表达式os.environ[‘PYTHONPATH’]。这个映射也能够用来更改系统环境变量。只是并不是全部系统都支持。

os.system函数用于运行外部程序。

也有一些函数能够运行外部程序。包含execv,它会退出python解释器。而且将控制权交给被运行的程序。还有popen,它能够创建与程序连接的类文件。

另外一个函数是windows特有的函数——os.statfile,它接受一般路径,即便空格也没问题。不像os.system那样须要将含空格的字符串放在引號下。

注意:在windows中,由os.systemos.startfile启动了外部程序之后。python程序仍然会继续执行。而在unix中。程序则会停止,等待os.system命令完毕。

os.sep模块变量是用于路径中的分隔符。

Unix的标准分隔符是/windows中的是\,而mac中的是:

pathsep用于分隔路径名:Unix使用’:’,windows使用’;’,mac os使用’::’;

urandom函数使用一个依赖于系统的“真”随机数的源。

假设正在使用的平台不支持它,会得倒NotImplementedError异常。

练习 重命名和删除文件

脚本内容

$ cat os-example-3.py

#File : os-example-3.py

import os

import string

def replace(file,search_for,replace_with):

        # replace strings in a text file

        back=os.path.splitext(file)[0]+".bak"

        temp=os.path.splitext(file)[0]+".tmp"

        try:

                #remove old temp file,if any

                os.remove(temp)

        except os.error:

                pass

        fi=open(file)

        fo=open(temp,'w')

        for s in fi.readlines():

                fo.write(string.replace(s,search_for,replace_with))

        fi.close()

        fo.close()

        try:

                #remove old backup file,if any

                os.remove(back)

        except os.error:

                pass

        # rename original to backup ...

        os.rename(file,back)

        # ... and temporary to original

        os.rename(temp,file)

# try it out!

file = "samples/sample.txt"

replace(file,"hello","signjing")

replace(file,"signjing","hello")

文件内容

$ cat samples/sample.txt

hello,signjing

hello,everyone

signjing,goodbye

运行结果

$ python os-example-3.py

$ cat samples/sample.txt

hello,hello

hello,everyone

hello,goodbye

练习 列举文件夹下的文件

$ ls samples/

sample.bak  sample.txt

脚本内容

$ cat os-example-5.py

# File: os-example-5.py

import os

import sys

print os.listdir(sys.argv[1])

ld=os.listdir(sys.argv[1])

for i in range(len(ld)):

        print str(ld[i])

运行结果

$ python os-example-5.py samples/

['sample.txt', 'sample.bak']

sample.txt

sample.bak

练习 更改当前工作文件夹

脚本内容

$ cat os-example-4.py

#File: os-example-4.py

import os

print os.getcwd()

os.chdir("..")

print os.getcwd()

os.chdir("..")

print os.getcwd()

os.chdir("../shoujitrunk")

print os.getcwd()

os.chdir(os.pardir)

print os.getcwd()

运行结果

$ python os-example-4.py

/home/ggz2/magiccube/mysh/pys

/home/ggz2/magiccube/mysh

/home/ggz2/magiccube

/home/ggz2/shoujitrunk

/home/ggz2

练习 创建和删除多个文件夹级

脚本内容

$ cat os-example-6.py

#File : os-example-6.py

import os

os.makedirs("1-dir")

os.makedirs("1-dir/2-dir")

os.makedirs("1-dir/2-dir/3-dir")

os.makedirs("1-dir/2-dir/3-dir/4-dir")

os.makedirs("1-dir/2-dir/3-dir/4-dir/5-dir")

fp=open("./1-dir/2-dir/3-dir/4-dir/5-dir/6-file","w")

fp.write("hello,")

fp.write("signjing")

fp.close()

with open("./1-dir/2-dir/3-dir/4-dir/5-dir/6-file","r") as tf:

        for f in tf.readlines():

                print str(f)

os.system("ls -Rl ./1-dir/*")

try:

        os.rmdir("./1-dir")

except Exception:

        print "dir not empty"

try:

        os.rmdir("./1-dir/2-dir/3-dir/4-dir/5-dir/")

except Exception:

        print "deep dir not empty"

os.remove("./1-dir/2-dir/3-dir/4-dir/5-dir/6-file")

try:

        os.rmdir("./1-dir")

except Exception:

        print "dir not empty"

try:

        os.rmdir("./1-dir/2-dir/3-dir/4-dir/5-dir/")

except Exception:

        print "deep dir not empty"

os.removedirs("./1-dir/2-dir/3-dir/4-dir/")

os.system("ls -l ./1-dir/*")

运行结果

$ python os-example-6.py

hello,signjing

./1-dir/2-dir:

总用量 4

drwxr-xr-x. 3 ggz2 tester 4096 7月   5 16:37 3-dir

./1-dir/2-dir/3-dir:

总用量 4

drwxr-xr-x. 3 ggz2 tester 4096 7月   5 16:37 4-dir

./1-dir/2-dir/3-dir/4-dir:

总用量 4

drwxr-xr-x. 2 ggz2 tester 4096 7月   5 16:37 5-dir

./1-dir/2-dir/3-dir/4-dir/5-dir:

总用量 4

-rw-r--r--. 1 ggz2 tester 14 7月   5 16:37 6-file

dir not empty

deep dir not empty

dir not empty

ls: 无法訪问./1-dir/*: 没有那个文件或文件夹

可见:

os.rmdir()用于删除单个空文件夹。

os.removedirs()则用于删除多级的空文件夹;

练习 获取文件信息

脚本内容

$ cat os-example-1.py

#File : os-example-1.py

import os

import time

file="os-example-1.py"

def dump(st):

        mode,ino,dev,nlink,uid,gid,size,atime,mtime,ctime=st

        print "- size:",size,"bytes"

        print "- owner:",uid,gid

        print "- created:",time.ctime(ctime)

        print "- last accessed:",time.ctime(atime)

        print "- last modified:",time.ctime(mtime)

        print "- mode:",oct(mode)

        print "- inode/dev:",ino,dev

st=os.stat(file)

print "stat",file

dump(st)

print

fp=open(file)

st=os.fstat(fp.fileno())

print "fstat",file

dump(st)

运行结果

$ python os-example-1.py

stat os-example-1.py

- size: 500 bytes

- owner: 504 501

- created: Wed Jun 25 14:46:08 2014

- last accessed: Sat Jul  5 16:39:43 2014

- last modified: Wed Jun 25 14:46:08 2014

- mode: 0100644

- inode/dev: 43127351 2055

fstat os-example-1.py

- size: 500 bytes

- owner: 504 501

- created: Wed Jun 25 14:46:08 2014

- last accessed: Sat Jul  5 16:39:43 2014

- last modified: Wed Jun 25 14:46:08 2014

- mode: 0100644

- inode/dev: 43127351 2055

练习 执行操作系统命令

脚本内容

$ cat os-example-8.py

#File : os-example-8.py

import os

if os.name=='nt':

        command = 'dir'

else:

        command = 'df -lh'

os.system(command)

执行结果

$ python os-example-8.py

文件系统              容量  已用  可用 已用%% 挂载点

/dev/sda2              97G  1.5G   90G   2% /

tmpfs                 3.8G     0  3.8G   0% /dev/shm

/dev/sda1             485M   30M  430M   7% /boot

/dev/sda7             709G   78G  596G  12% /home

/dev/sda3              49G  180M   46G   1% /tmp

/dev/sda5              49G  328M   46G   1% /var

练习 退出当前进程

脚本内容

$ cat os-example-9.py

#File : os-example-9.py

import os

import sys

try:

        sys.exit(1)

except SystemExit,value:

        print "caught exit(%s)" %value

try:

        os._exit(2)

except SystemExit,value:

        print "caught exit(%s)" %value

print "Bye"

运行结果

$ python os-example-9.py

caught exit(1)

练习 处理文件名称

脚本内容

$ cat os-path-example-1.py

#File : os-path-example-1.py

import os

filename="samples/sample.txt"

print "using",os.name,"..."

print "split","=>",os.path.split(filename)

print "splitext","=>",os.path.splitext(filename)

print "dirname","=>",os.path.dirname(filename)

print "basename","=>",os.path.basename(filename)

print "join","=>",os.path.join(os.path.dirname(filename),os.path.basename(filename))

运行结果

$ python os-path-example-1.py

using posix ...

split => ('samples', 'sample.txt')

splitext => ('samples/sample', '.txt')

dirname => samples

basename => sample.txt

join => samples/sample.txt

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mengfanrong/p/4638087.html