标准库:有些收藏夹

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. Meld Diff for windows 安装和配置

    Meld Diff for windows 安装和配置 假设你在ubuntu 正在开发中, meld diff 此工具你肯定不会感到陌生. 而且很容易使用. 在网上看 meld for Windows ...

  2. hdu 1290 竭诚为杭州电礼物50周年

    专门为杭州电50周年礼事 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Tot ...

  3. ssis t-sql返回值

    原文:ssis t-sql返回值 sql类似如下,不需要使用return 语句,SQL语句的ConnectionType必须是"ADO.NET" select @proID=fie ...

  4. NSIS:静默释放文件并运行 制作绿色单文件软件

    原文 NSIS:静默释放文件并运行 制作绿色单文件软件 现在所谓的绿色单文件软件,大多与以下代码原理相似:把软件运行需要的文件封装为一个EXE文件,双击时释放到某个目录(大多是TEMP)并运行主程序文 ...

  5. iOS 生成随机颜色(UIColor)

    #import <UIKit/UIKit.h> @interface UIColor (RandomColor) +(UIColor *) randomColor; @end #impor ...

  6. 纯CSS3实现的图片滑块程序 效果非常酷

    原文:纯CSS3实现的图片滑块程序 效果非常酷 之前我们经常会看到很多利用jQuery实现的焦点图插件,种类太多了,今天我想给大家分享一款利用纯CSS3实现的图片滑块应用,完全是利用CSS3的相关特性 ...

  7. Java Web整合开发(3) -- Servlet

    Servlert基本程序架构: (FirstServlet.java + web.xml) FirstServlet.java package com.helloben.servlet; import ...

  8. C语言功能 --C

    功能名称: cabs 动力 能够: 计算绝对复数值 使用 法国: double cabs(struct complex z); 程序示例: #include <stdio.h> #incl ...

  9. 蜘蛛牌 (DFS)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1584 全部状态都判断一遍 代码: #include <stdio.h> #include ...

  10. BroadcastReceiver.PendingResult类别

    java.lang.Object android.content.BroadcastReceiver.PendingResul 类概述 状态的结果正在等待一个广播接收器.在BroadcastRecei ...