1)調用系統命令
調用SHELL命令nslookup,將執行的結果保存到變量result_nslook中
import os cmd='nslookup %s' % hostname handle=os.popen(cmd , 'r') result_nslook=handle.read()
調用shell命令但是不需要獲取返回結果
import os cmd='ls' os.system(cmd)
2)Python 的字符串處理
去掉前后空格
input = open('hostlist_ip' , 'r') for hostname in input.xreadlines(): #按行讀文件到hostname中 hostname=hostname.strip() hostlist.append(hostname) input.close()
將讀入的一個字符串數組按照空格划分為list
temp=display.split() for seg in temp: if seg[0:5]=='time=': output.write(seg.lstrip('time=').strip()+'\t') delayRec.append(seg.lstrip('time='))
3)文件操作
打開文件進行讀寫
import os input=open(filename ,'r') #讀文件 output=open(filename ,'w') #寫文件 output=open(filename,'a') #追加寫文件
遍歷文件夾操作
import os for root, dirs, files in os.walk(path, topdown=False): #hanlde file for name in files: if name[:-3] = 'exe': print name
#刪除文件
top='mydata/' for root,dir,files in os.walk(top,topdown=False): for name in files: os.remove(os.path.join(root,name)) os.rmdir('mydata') os.mkdir('mydata')
列出文件
import os os.listdir("c:\\music\\_singles\\") ['a_time_long_forgotten_con.mp3', 'hellraiser.mp3', 'kairo.mp3', 'long_way_home1.mp3', 'sidewinder.mp3', 'spinning.mp3']
4)如果將Blob存儲到SQLite中
有時候我們需要將Blob或者二進制文件對象存儲到SQLite數據庫中,下面這個例子演示了,Python中是如何實現的:
import os import sqlite class Blob: """Automatically encode a binary string.""" def __init__(self, s): self.s = s def _quote(self): return "'%s'" % sqlite.encode(self.s) db = sqlite.connect("test.db") cursor = db.cursor() cursor.execute("CREATE TABLE t (b BLOB);") s = "\0"*50 + "'"*50 cursor.execute("INSERT INTO t VALUES(%s);", Blob(s)) cursor.execute("SELECT b FROM t;") b = cursor.fetchone()[0] assert b == s # b is automatically decoded db.close() os.remove("test.db")