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

Python3文件(文件夹)基本操作

时间:2023-03-26 00:37:03 Python

相关模块osos.pathshtilpathlib(3.4版本新增)判断文件(文件夹)是否存在的基本操作。os.path.exists(pathname)#newpathlib.Path(pathname).exists()判断路径名是否为文件。os.path.isfile(pathname)#newpathlib.Path(pathname).is_file()判断路径名是否为目录。os.path.isdir(pathname)#newpathlib.Path(pathname).is_dir()创建文件。os.mknod(filename)#Windows下不可用open(filename,"w")#记得关闭#newpathlib.Path(filename).touch(mode=438,exist_ok=True)复制文件。shutil.copyfile("oldfile","newfile")#oldfile和newfile只能是文件,目标文件会被覆盖shutil.copy("oldfile","newfile")#oldfile只能是文件,newfile可以是files,也可以是删除文件的目标目录。os.remove(filename)#newpathlib.Path(pathname).unlink()清空文件。file=open("test.txt",w)file.seek(0)file.truncate()#注意文件指针的位置file.close()创建目录。os.mkdir(pathname)#创建单级目录#newpathlib.Path(pathname).mkdir()#创建单级目录os.makedirs(pathname)#递归创建多级目录复制目录。#olddir和newdir都只能是目录,newdir不能存在shutil.copytree("olddir","newdir")重命名文件或目录。os.rename(oldname,newname)pathlib.Path(oldname).rename(newname)移动文件或目录shutil.move(oldpath,newpath)删除目录os.rmdir("dir")#不能删除非空目录#newpathlib.Path("dir").rmdir()#shutil.rmtree可以删除非空目录,也可以在目录打开时删除#约等于'rd/Q/Sdir'shutil.rmtree("dir")切换目录os.chdir(newpath)开启普通模式。'r':只读(默认。如果文件不存在则抛出错误。)'w':只写(如果文件不存在,将自动创建文件。)'a':追加'r+':read-writeFromfullpathnametopathandfilename>>>pathfile=r'D:\abc\def\ghi.txt'>>>os.path.dirname(pathfile)'D:\\abc\\def'#newstr(Path(pathfile).parent)>>>os.path.basename(pathfile)'ghi.txt'#newPath(pathfile).name获取文件大小os.path.getsize(pathfile)#The单位是字节(Byte)#oros.stat(pathfile).st_size#newpathlib.Path(pathfile).stat().st_size获取文件创建/修改/访问时间。os.path.getctime(pathfile)#创建时间os.path.getmtime(pathfile)#修改时间os.path.getatime(pathfile)#访问时间#newpathlib.Path(pathfile).stat().st_ctime#创建时间pathlib.Path(pathfile).stat().st_mtime#修改时间pathlib.Path(pathfile).stat().st_atime#获取当前文件目录绝对路径的访问时间os.path.abspath('.')#newstr(pathlib.Path('.').resolve())文件同步fileObj.write(text)fileObj.flush()os.fsync(fileObj.fileno())获取文件扩展名>>>os.path.splitext(r'D:\tmp\3.jpg')[1]'.jpg'>>>os.path.splitext('3.jpg')[1]'.jpg'#newpathlib.Path(r'D:\tmp\3.jpg').suffix本文来自walker快照