标准库:有些收藏夹

os

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

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

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

函数/变量

描写叙述

environ

对环境变量进行映射

system(command)

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

sep

路径中的分隔符

pathsep

分隔路径的分隔符

linesep

行分隔符(‘\n’,’\r’,’\r\n’)

urandom(n)

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

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

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

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

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

注意:在windows中,由os.system或os.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

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

python基础课程_学习笔记20:标准库:有些收藏夹——os的更多相关文章

  1. python基础课程_学习笔记15:标准库:有些收藏夹——fileinput

    标准库:有些收藏夹 fileinput 重要功能 性能 叙述性说明 input([files[,inplace[,backup]]) 便于遍历多个输入流中的行 filename() 返回当前文件的名称 ...

  2. python基础课程_学习笔记13:标准库:有些收藏夹——sys

    标准库:有些收藏夹 sys sys这个模块可以让你访问和python解释器联系紧密的变量和函数. sys模块中一些重要的函数和变量 函数/变量 描写叙述 argv 命令行參数,包含脚本名称 exit( ...

  3. python基础课程_学习笔记26:编程的乐趣

    编程的乐趣 编程柔术 当你坐下来,打算如何组织计划要定时,具体程序,然而,无论什么经验.在实现时间的函数的,你会逐渐学会了原来的设计,实用的新知识.我们不应该忽视沿途汲取的教训,相反,它们用于其他设计 ...

  4. python基础课程_学习笔记21:文件和材料

    文件和材料 打开文件 open功能是用来打开文件,语法例如,下面的: open([name[,mode[,buffering]]) open函数使用一个文件名称作为唯一的强制參数,然后返回一个文件对象 ...

  5. python基础教程_学习笔记14:标准库:一些最爱——re

    标准库:一些最爱 re re模块包括对正則表達式的支持,由于以前系统学习过正則表達式,所以基础内容略过,直接看python对于正則表達式的支持. 正則表達式的学习,见<Mastering Reg ...

  6. python基础教程_学习笔记19:标准库:一些最爱——集合、堆和双端队列

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/signjing/article/details/36201499 标准库:一些最爱 集合.堆和双端队 ...

  7. python基础教程_学习笔记18:标准库:一些最爱——shelve

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/signjing/article/details/36029981 标准库:一些最爱 shelve S ...

  8. python基础教程_学习笔记12:充电时刻——模块

    充电时刻--模块 python的标准安装包含一组模块,称为标准库. 模块 >>> import math >>> math.sin(0) 0.0 模块是程序 不论什 ...

  9. python基础课程_2学习笔记3:图形用户界面

    图形用户界面 丰富的平台 写作Python GUI程序前,须要决定使用哪个GUI平台. 简单来说,平台是图形组件的一个特定集合.能够通过叫做GUI工具包的给定Python模块进行訪问. 工具包 描写叙 ...

随机推荐

  1. gradle中使用cobertura做代码覆盖(转)

    gradle很好用,但是默认是没有代码覆盖功能的,只好自己写.曾经在网上找到过别人的一段脚本,虽然也能用,但是有一些不爽的地方,一个原因是它不支持对层级工程中全部代码的覆盖,另一个原因是它用替换bui ...

  2. 依据Uri获得sd卡图片

    <pre name="code" class="java">String mBigImage = URLEncoder.encode(mImageU ...

  3. Redis集群方案及实现

    在作出Redis群集解决方案,他跑了小半个.行表现得非常稳定在几乎相同的经历与大家分享,我写在前面的文章数据在线服务的一些探索经验,能够做为背景阅读 应用 我们的Redis集群主要承担了下面服务:1. ...

  4. js调用跨域

    web aapi 初体验 解决js调用跨域问题   跨域界定 常见跨域: 同IP不同端口: http:IP:8001/api/user     http:IP:8002/api/user 不同IP不同 ...

  5. mahout源码KMeansDriver分析之五CIMapper初探

    接着上篇,继续分析代码.下面就到了MR的循环了,这里MR应该算是比较好理解的,重点是退出循环的条件设置,即如何判断前后两次中心点误差小于给定阈值. 首先,while循环: while (iterati ...

  6. 提高duilib的richedit控制的一些特征

    转载请注明原始出处.谢谢~~:http://blog.csdn.net/zhuhongshu/article/details/41208207 假设要使用透明异形窗口功能,首先要改进duilib库让他 ...

  7. 解决 Mybatis 元素类型为 "resultMap" 的内容必须匹配 "(constructor?,id*,result*,association*,collection*,discriminat

    在配置 mybatis mapper.xml文件时, 一不小心就会报如下类似的异常: Caused by: org.springframework.beans.factory.BeanCreation ...

  8. Linux 常用命令汇总

    1.shutdown -s 时间 如果是想马上关机就直接输入0或者now: 2.init 0 这个是运行级别关机: 3.halt 这个命令不是很好用: 4.power off 这个命令也是很好用的. ...

  9. 用Owin Host实现脱离IIS跑Web API单元测试

    开发笔记:用Owin Host实现脱离IIS跑Web API单元测试   今天在开发一个ASP.NET Web API项目写单元测试时,实在无法忍受之前的笨方法,决定改过自新. 之前Web API的单 ...

  10. 第四章:Django 的模板系统(转)

    在之前的章节中,你可能觉得例子中视图返回文本有点不妥.即是, HTML 是直接写在 Python 代码中的.     这种做法会导致这些问题:     要做任何设计上的更改就必须改写 Python 代 ...