python os模块学习
脚本主要从<Python+Standard+Library中文版_IT168文库.pdf>抄下来的记录.
此处为os模块内容,学习完这些,可以完成一些日常运维工作吧.
#!/usr/bin/python
#coding=utf-8
#time: 2013-10-02
#os_example_3.py
#实现os modules重命名和删除文件需要
#os.rename and os.remove
import os
import string
#定义函数,实现文件复制功能
def replace(file, search_for, replace_with):
#replace string in a text file
back = os.path.splitext(file)[0] + ".bak"
temp = os.path.splitext(file)[0] + ".tmp"
#os.path.splitext("/tmp/test/mojigan.txt")
#('/tmp/test/mojigan', '.txt')
#文件删除,无论有没有
try:
#remove old temp file,if any
os.remove(temp)
except os.error:
pass
#<open file 'samples/sample.txt', mode 'r' at 0x2b4cbde50af8>
#<open file 'samples/sample.tmp', mode 'w' at 0x2b4cbde50b70>
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", "tjena")
replace(file, "tjena", "hello")
#!/usr/bin/python
#coding=utf-8
#os_example_4.py
#主要使用目录更改变换
#os.getcwd and os.chdir为os模块的方法,带()
#os.pardir 只是os模块的属性,值为'..',它没有括号的
import os
print "当前目录位置为: " + os.getcwd()
os.chdir("/tmp")
print "现在已经更改目录操作,再查看当前目录: " + os.getcwd()
os.chdir("/root/python/source")
print "初始回刚开始的目录位置: " + os.getcwd()
os.chdir(os.pardir)
print "呵呵,现在在上一级目录,当前为: " + os.getcwd()
[root@green source]# python os_example_4.py
当前目录位置为: /root/python/source
现在已经更改目录操作,再查看当前目录: /tmp
初始回刚开始的目录位置: /root/python/source
呵呵,现在在上一级目录,当前为: /root/python
#/usr/bin/python
#coding=utf-8
#如果脚本有中文注释,请使用coding处理,且必须放在第二行
#os_example_5.py
#time 2013-10-02
#主要列出目录下的文件列表
#os.listdir
import os
dirname = "/"
for file in os.listdir(dirname):
print file
转载于:https://blog.51cto.com/teemomo/1304251