当前位置: 首页 > 后端技术 > Python

Python之OS模块39个常用函数详解

时间:2023-03-26 13:47:05 Python

作者:小武哥来源:AI入门学习os,语义操作系统,所以这个模块是操作系统相关的函数,用来处理文件和目录,这些都是我们每天需要手动完成的操作,比如新建文件夹,获取文件列表,删除文件,获取文件大小,重命名文件,获取文件修改时间等等。这个模块包含大量的操作系统操作函数,选取常用的进行分析,希望对大家有所帮助。os下有很多函数,调用方式一般是os.name,比较特殊的是Path。Path模块是OS的一个子模块,下面有很多函数,调用方式一般是os.path.isfile。刚接触的人可能看不懂,需要注意。loadimportos查看os下的函数print(dir(os))查看os.path下的函数print(dir(os.path))01、os.name()说明:显示当前使用的平台,'nt'表示Windows,'posix'表示Linux语法:os.nameos.name'nt'02,os.getcwd()描述:返回当前进程的工作目录。语法:os.getcwd()os.getcwd()'C:Userswuzhengxiang'03,os.chdir()描述:改变当前工作目录到指定路径。语法:os.chdir(path)查看当前目录os.getcwd()'C:Userswuzhenxiang'#重置当前工作空间os.chdir('C:/Users/wuzhengxiang/Desktop/StockDataAnalysis')查看当前目录再次,变成了新的os.getcwd()'C:UserswuzhenxiangDesktopstockdataanalysis'04,os.makedirs()说明:该方法用于递归创建目录。与mkdir()类似,但会创建所有需要包含子目录的中级文件夹。语法:os.makedirs(path,mode=0o777)os.makedirs('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis/1122',mode=0o777)05、os.mkdir()说明:在数字权限模式下创建一个目录。默认模式是0777(八进制)。语法:os.mkdir(path[,mode])新建目录2233os.mkdir('C:/Users/wuzhenxiang/Desktop/stockdataanalysis/2233',mode=0777)06,os.listdir()description:列出目录下的所有文件和文件夹语法:os.listdir(path)os.listdir('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis')['ETFResearch.py??','foo.txt','pi.txt','render.html']os.listdir('.')['ETFresearch.py??','foo.txt','pi.txt','render.html']07、os.remove()说明:用于删除指定路径文件。如果指定的路径是一个目录,将抛出OSError。语法:os.remove(path)os.remove('C:/Users/zhengxiang.wzx/Desktop/timg.jpg')08.os.rename()描述:命名一个文件或目录,并重命名对应的文件命名语法:os.rename(src,dst)参数src--修改的目录名dst--修改后的目录名空间设置data_path='C:/Users/zhengxiang.wzx/Desktop/微博情感识别'os.chdir(data_path)#设置工作空间os.getcwd()'C:Userszhengxiang.wzxDesktopWeiboemotionrecognition'os.rename("图片下载.py","图片下载1.py")09,os.renames()说明:用于递归重命名目录或文件。类似于重命名()。可以重命名文件或文件的上级目录名语法:os.renames(old,new)参数:old--重命名的目录new--文件或目录的新名称。它甚至可以是包含在目录中的文件,或完整的目录树。os.chdir('C:/Users/wuzhenxiang/Desktop/Python知识点总结')os.getcwd()文件夹和文件同时命名os.renames("test/Python63内置函数details.py","test2/内置函数详解.py")os.listdir()['kaggle','test2','股票分析','课程资源'10,os.linesep()描述:当前platform用于分隔(或终止)行String。它可以是单个字符,例如POSIX上的“n”,也可以是多个字符,例如Windows上的“rn”。写入以文本模式(默认)打开的文件时,不要使用os.linesep作为行终止符,而是在所有平台上使用'n'。语法:os.linesepos.linesep'rn'11,os.pathsep()描述:操作系统通常用于分隔搜索路径(如PATH)不同部分的字符,如POSIX上的':'和'在Windows上;'.在os.path中也可用。语法:os.pathsepos.pathsep';'12,os.close()描述:关闭指定文件描述符fd语法:os.close(fd)fd=os.open("foo.txt",os.O_RDWR|os.O_CREAT)os.write(fd,bytes("Thisistest",encoding="utf8"))os.close(fd)13,os.stat()描述:获取文件或目录信息语法:os.stat(path)os.stat('C:/Users/wuzhenxiang/Desktop/股票数据分析pi.txt')os.stat_result(st_mode=33206,st_ino=22236523160361562,st_dev=2419217970,st_nlink=1,st_uid=0,st_gid=0,st_size=53,st_atime=1589638199,st_mtime=1589638199,st_ctime=1581868007)14.os.sep()描述:显示当前平台下的路径分隔符,POSIX上为'/',Windows上为'语法:os.sepos.sep''15,os.path.abspath()描述:返回文件的绝对路径语法:os.path.abspath(path)Excelfileos.path.abspath('all_data.xlsx')'C:Userszhengxiang.wzxall_data.xlsx'图片文件os.path.abspath('IMG_7358.JPG')'C:Userszhengxiang.wzxIMG_7358.JPG'16、os.path.basename()description:返回文件名,纯字符串处理逻辑,路径错误也可以path.commonprefix()描述:返回列表(多条路径)中,所有路径共有的最长路径语法:os.path.commonprefix(list)os.path.commonprefix(['http://c.biancheng.net/python...','http://c.biancheng.net/shell/'])'http://c.biancheng.net/'os.path.commonprefix(['http://bianc/python/aaa','http://c.biancheng.net/shell/'])'http://'18,os.path.dirname()描述:返回文件路径语法:os.path.dirname(path)os.path.dirname('C://my_file.txt')'C://'os.path.dirname('C://python//my_file.txt')'C://python'19,os.path.exists()说明:如果path路径存在,返回True;如果路径路径不存在,则返回False语法:os.path。exists(path)os.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/pi.txt')Trueos.path.exists('C:/Users/wuzhengxiang/Desktop/股票数据分析/')Trueos.path.exists('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis/pi_01.txt')Fals20,os.path.lexists()说明:路径存在则返回True,路径存在则返回True已损坏,不存在,返回False。语法:os.path.lexistsos.path.lexists('C:/Users/wuzhenxiang/Desktop/股票数据分析/pi.txt')Trueos.path.lexists('C:/Users/wuzhenxiang/Desktop/股票数据分析/pi_01.txt')False21,os.path.expanduser()描述:将路径中包含的“~”和“~user”转换为用户目录语法:os.path.expanduser(path)os.path.expanduser('~/wuzhenxiang/Desktop/StockDataAnalysis/')'C:Userswuzhenxiang/wuzhenxiang/Desktop/StockDataAnalysis/'22.os.path.expandvars()描述:根据值替换path中包含的“$”环境变量名称”和“${name}”语法:os.path.expandvars(path)os.environ['KITTIPATH']='D:/thunder'path='$KITTIPATH/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'os.path.expandvars(path)'D:/thunder/train/2011_09_26_drive_0001_sync/proj_depth/velodyne_raw/image_02/0000000013.png'23,os.path.getatime()描述:返回最新的accesstime(floattypeseconds),秒数si进入访问时间的纪元。语法:os.path.getatime(path)os.path.getatime('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis/pi.txt')1589638199.134324824,os.path.getmtime()描述:返回最新文件修改时间,从纪元到访问时间的秒数。语法:os.path.getmtime(path)os.path.getmtime('C:/Users/wuzhenxiang/Desktop/stockdataanalysis/pi.txt')1583069050.814894225,os.path.getctime()描述:返回文件路径创建时间,从纪元到访问时间的秒数。语法:os.path.getctime(path)os.path.getctime('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis/pi.txt')1581868007.612331926,os.path.getsize()描述:返回文件大小,如果文件不存在,返回错误语法:os.path.getsize(path)os.path.getsize('C:/Users/wuzhenxiang/Desktop/stockdataanalysis/test.gif')112867727,os.path.isabs()描述:判断是否为绝对路径,即在WIndow系统下,如果输入字符串以“/”开头,os.path.isabs()将返回True语法:os.path.isabs(path)os.path.isabs('D:/thunder')Trueos.path.isabs('D:thunder')Falseos.path.isabs('D:thunder')True28、os.path.isfile()说明:判断路径是否为文件语法:os.path.isfile(path)文件不存在returnFalseos.path.isfile("C:/Users/wuzhenxiang/Desktop/stockdataanalysis/pi_01.txt")Falseos。path.isfile("C:/Users/wuzhengxiang/Desktop/StockDataAnalysis/pi.txt")True#不是文件returnFalseos.path.isfile("C:/Users/wuzhengxiang/Desktop/股票数据分析/")False29,os.path.isdir()描述:判断路径是否为目录语法:os.path.isdir(path)os.path.isdir('C:/Users/wuzhenxiang/Desktop/股票数据分析')Trueos.path.isdir('C:/Users/wuzhenxiang/Desktop/股票数据分析1')Falseos.path.isdir('C:/Users/wuzhenxiang/Desktop/股票数据分析/pi.txt')False30、os.path.join()说明:将目录和文件名组合成一个路径,1.如果每个组件名的首字母不包含'/',函数会自动添加,2.如果一个组件是绝对路径,则其中前面的所有组件都会被丢弃,3.如果最后一个组件为空,则生成的路径以'/'分隔符结尾语法:os.path.join(path1[,path2[,...]])os.path.join('C:/Users','wuzhenxiang/Desktop/','股数据分析')'C:/Userswuzhenxiang/Desktop/股数据分析'Path1='home'Path2='develop'Path3='code'Path10=Path1+Path2+Path3Path20=os.path.join(Path1,Path2,Path3)print('Path10=',Path10)print('Path20=',Path20)Path10=homedevelopcodePath20=homedevelopcode31,os.path。normcase()描述:转换路径的大小写和斜杠语法:os.path.normcase(path)os.path.normcase('D:Pythontestdata.txt')'d:pythontestdata.txt'os.path.normcase('c:/WINDOWSsystem64')'c:windowssystem64'32、os.path.normpath()描述:norma化路径字符串格式语法:os.path.normpath(path)os.path.normpath('c://windowsSystem32../Temp/')'c:windowsTemp'33,os.path.realpath()描述:返回path的真实路径语法:os.path.realpath(path)os.path.relpath('C:UsersAdministratcodeTRYtest.ipynb','CodeTRY')'.....AdministratcodeTRYtest.ipynb'34,os.path.relpath()说明:从当前目录或起始目录返回记录(可选)获取路径的相对路径。这只是路径计算,没有文件系统访问来确认路径或开始的存在或属性。语法:os.path.relpath(path[,start])os.path.relpath('C:/Users/wuzhenxiang/Desktop/股票数据分析test.gif')'test.gif'35,os.path.samefile()描述:判断目录或文件是否相同语法:os.path.samefile(path1,path2)os.path.samefile('C:Users','C:Users')Trueos.path.samefile('C:Users','C:/Users')Trueos.path.samefile('C:Users','C:/Users/wuzhenxiang')False36??,os.path.split()说明:将路径拆分为dirname和basename,return元组语法:os.path.split(path)os.path.split('D:Pythontestdata.txt')('D:Pythontest','data.txt')37,os.path.splitdrive()37、os.path.splitdrive()说明:一般在windows下使用,返回一个由驱动器名和路径组成的元组语法:os.path.splitdrive(path)os.path.splitdrive('C:/Users/zhengxiang.wzx/IMG_7358.JPG')('C:','/Users/zhengxiang.wzx/IMG_7358.JPG')38,os.path.splitext()描述:拆分路径,返回路径名和文件扩展名的元组语法:os.path.splitext(路径)os.path.splitext('C:/Users/zhengxiang.wzx/IMG_7358.JPG')('C:/Users/zhengxiang.wzx/IMG_7358','.JPG')39、os.path.walk()描述:遍历路径,进入每个目录时调用访问函数。visit函数必须有3个参数(arg,dirname,names),dirname代表当前目录的目录名,names代表当前目录下所有文件名,args为walk第三个参数的语法:os.path.walk(path,visit,arg)list(os.walk(abs_cur_dir))[('C:/Users/wuzhenxiang/Desktop/StockDataAnalysis',['1122'],['ETFResearch.py??','foo.txt','pi.txt','render.html','test.gif']),('C:/Users/wuzhenxiang/Desktop/股票数据分析1122',[],[])]穷举一个文件夹下的所有文件,得到文件的目录名abs_cur_dir='C:/Users/wuzhenxiang/Desktop/股票数据分析'file_url=[]fordirs,folders,os.walk(abs_cur_dir)中的文件:foriinfiles:file_url.append(os.path.join(dirs,i))file_url['C:/Users/wuzhenxiang/Desktop/股票数据分析ETFresearch.py??','C:/Users/wuzhenxiang/Desktop/股票数据分析foo.txt','C:/Users/wuzhenxiang/Desktop/股票数据分析pi.txt','C:/Users/wuzhenxiang/Desktop/股票数据分析render.html','C:/Users/wuzhenxiang/Desktop/股票数据分析测试.gif']pathlib也可以实现类似