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