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

标准库:有些收藏夹

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

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

时间: 2024-08-06 03:39:57

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

python基础教程_学习笔记20:标准库:一些最爱——os

标准库:一些最爱 os os模块为你提供了访问多个操作系统服务的功能. os和它的子模块os.path还包括一些用于检查.构造.删除目录和文件的函数,以及一些处理路径的函数. os模块中一些重要函数和变量 函数/变量 描述 environ 对环境变量进行映射 system(command) 在子shell中执行操作系统命令 sep 路径中的分隔符 pathsep 分隔路径的分隔符 linesep 行分隔符('\n','\r','\r\n') urandom(n) 返回n字节的加密强随机数据 os

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

标准库:有些收藏夹 sys sys这个模块可以让你访问和python解释器联系紧密的变量和函数. sys模块中一些重要的函数和变量 函数/变量 描写叙述 argv 命令行參数,包含脚本名称 exit([arg]) 退出当前程序,可选參数为给定的返回值或者错误信息 modules 映射模块名字到加载模块的字典 path 查找模块所在文件夹的文件夹名列表 platform 类似sunos5或者win32的平台标识符 stdin 标准输入流--一个类文件对象 stdout 标准输出流--一个类文件对象

python基础教程_学习笔记16:标准库:一些最爱——random

标准库:一些最爱 random random模块包括返回随机数的函数,可以用于模拟或者用于任何产生随机输出的程序. 事实上,所产生的数字都是伪随机数,它们以一个可预测的系统作为基础,除非是为了强加密的目标,否则这些随机数还是足够随机的.如果真的需要随机性,可以使用os模块的urandom函数. 重要函数 函数 描述 random() 返回0<=n<1之间的随机实数n,其中0<n<=1 getrandbits(n) 以长整型形式返回n个随机位(二进制数) uniform(a,b) 返

python基础教程_学习笔记15:标准库:一些最爱——fileinput

标准库:一些最爱 fileinput 重要的函数 函数 描述 input([files[,inplace[,backup]]) 便于遍历多个输入流中的行 filename() 返回当前文件的名称 lineno() 返回当前(累计)的名称 filelineno() 返回当前文件的行数 isfirstline() 检查当前行是否是文件的第一行 isstdin() 检查最后一行是否来自sys.stdin nextfile() 关闭当前文件,移动到下一个文件 close() 关闭序列 fileinput

python基础教程_学习笔记17:标准库:一些最爱——time

标准库:一些最爱 time time模块所包含的函数能够实现以下功能: 获取当前时间.操作系统时间和日期.从字符串读取时间以及格式化时间为字符串. 日期可以用实数(从"新纪元"的1月1日0点开始计算到现在的秒数,新纪元是一个与平台相关的年份,对unix来说是1970年),或者是包含有9个整数的元组. 日期元组的字段含义 如元组: (2008,1,21,12,2,56,0,21,0) 表示2008年1月21日12时2分56秒,星期一,且是当年的第21天(无夏令时). 索引 字段 值 0

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

标准库:一些最爱 re re模块包含对正则表达式的支持,因为曾经系统学习过正则表达式,所以基础内容略过,直接看python对于正则表达式的支持. 正则表达式的学习,见<Mastering Regular Expressions>(精通正则表达式) re模块的内容 最重要的一些函数 函数 描述 compile(pattern[,flags]) 根据包含正则表达式的字符串创建模式对象 search(pattern,string[,flags]) 在字符串中寻找模式 match(pattern,st

python基础教程_学习笔记13:标准库:一些最爱——sys

标准库:一些最爱 sys sys这个模块让你能够访问与python解释器联系紧密的变量和函数. sys模块中一些重要的函数和变量 函数/变量 描述 argv 命令行参数,包括脚本名称 exit([arg]) 退出当前程序,可选参数为给定的返回值或者错误信息 modules 映射模块名字到载入模块的字典 path 查找模块所在目录的目录名列表 platform 类似sunos5或者win32的平台标识符 stdin 标准输入流--一个类文件对象 stdout 标准输出流--一个类文件对象 stde

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

标准库:一些最爱 集合.堆和双端队列 集合 集合Set类位于sets模块中. >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> set(range(10)) set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 集合是由序列(或其他可迭代的对象)构建的.主要用于检查成员资格,因此,副本是被忽略的: >>> range(10)*2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9

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

标准库:一些最爱 shelve Shelve唯一有趣的函数是open.在调用它的时候(使用文件名作为参数),它会返回一个Shelf对象,可以用它来存储内容.只需要把它当作普通的字典(但是键一定要作为字符串)来操作即可,在完成工作之后,调用它的close方法. 意识到shelve.open函数返回的对象并不是普通的映射是很重要的. >>> import shelve >>> s=shelve.open('a.txt') >>> s['x']=['a','