本文实例为大家分享了python os模块在系统管理中的应用代码,供大家参考,具体内容如下
#临时文件
impor<div style="color:transparent">本文来源gaodai.ma#com搞##代!^码@网*</div>t tempfile tempfile.gettempdir() #'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp' tempfile.mkstemp() #(4, 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp9zc5ipzr') tempfile.mkdtemp() #'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\tmp94wxuh44'
#操作系统命令
import os os.chdir(r'd:') #切换到目录(r为转义字符) os.listdir(r'd:') #显示目录下的所有文件 os.makedirs(r'd:\1\1') #创建路径的所有文件 os.mkdir(r'd:\1') #创建文件
#查找
import glob glob.glob('d:*.txt') #目录下的txt文件 glob.glob('d:*n.txt') #目录下的以n.txt结尾的文件
#遍历目录
import re,os,os.path def run(top): for(dirname,subdirs,files) in os.walk(top): print("["+dirname+"]") for fname in files: print(os.path.join(dirname,fname)) if __name__=='__main__': run(r'd:\1')
调用以下函数时要注意以下两点
(1)调用任何函数之前,要先调用start()函数。要有d:\ptest、和ptest下有三个目录:document、files、temp,才能进行其他操作
(2)调用(1)-(8)函数,只需要test8()
例如:解决第八个问题
start() test8()
****d:\ptest、ptest下有三个目录:document、files、temp。
import os,glob,shutil def start(): if os.path.exists(r'd:\ptest'): pass else: os.makedirs(r'd:\ptest\document') os.makedirs(r'd:\ptest\files') os.makedirs(r'd:\ptest\temp')
(1)将c:\windows目录下的所有ini文件复制到document中。
def test1(): file_lists=glob.glob('c:\windows\*.ini') for file in file_lists: shutil.copy(file,r'd:\ptest\document')
(2)将c:\windows目录下以’n’开头的所有文件复制到files中。
def test2(): file_lists=glob.glob('c:\windows\*') #temp=[]#以'n'开头的所有文件 for file in file_lists: files=file.replace('c:\windows\\','') if files.startswith('n'): shutil.copy(file,r'd:\ptest\files') #temp.append(file)
(3)判断files文件夹中是否有notepad.exe文件,如果有,将其复制到temp中,并改名为mypad.exe。
def test3(): if os.path.exists(r'd:\ptest\files\notepad.exe'): shutil.copy(r'd:\ptest\files\notepad.exe',r'd:\ptest\temp\mypad.exe') else: print("没有notepad.exe文件")
(4)判断document文件夹中是否有win.ini文件,如果有将其移动到temp中。
def test4(): if os.path.exists(r'd:\ptest\document\win.ini'): shutil.move(r'd:\ptest\document\win.ini',r'd:\ptest\temp') else: print("没有win.ini文件")
(5)判断document文件夹中是否有system.ini文件,如果有将其以system.inf的名称复制到temp中,然后删除原文件。
def test5(): if os.path.exists(r'd:\ptest\document\system.ini'): #复制删除 shutil.copy(r'd:\ptest\document\system.ini',r'd:\ptest\temp\system.inf') os.remove(r'd:\ptest\document\system.ini') #移动 #shutil.move(r'd:\ptest\document\system.ini',r'd:\ptest\temp') else: print("没有system.ini文件")
(6)在document下新建mydir文件夹,并将temp中的所有文件复制到mydir下。
def test6(): if os.path.exists(r'd:\ptest\document\mydir'): pass else: os.mkdir(r'd:\ptest\document\mydir') '''#遍历找出文件 for (dirpath,dirnames,filenames)in os.walk(r'd:\ptest\document'): for file in filenames: print(os.path.join(dirpath,file)) ''' file_lists=glob.glob('d:\ptest\document\*') for file in file_lists: if os.path.isfile(file): if os.path.exists(file): print("文件已存在") else: shutil.copy(file,r'd:\ptest\document\mydir')