python os模块 对文件夹、文件(文件操作函数)
os.getcwd() #返回当前工作路径os.path.isabs() #判断是否是绝对路径os.path.isfile() #检验给出的路径是否是一个文件os.path.isdir() #检验给出的路径是否是一个目录os.sep #文件的路径分隔符 如:在windows上是 '\' 而在Linux上是 '/'os.walk() #文件遍历 如:def file_name(file_dir): for root, dirs, files in os.walk(file_dir): print('root_dir:', root) # 当前目录路径 print('sub_dirs:', dirs) # 当前路径下所有子目录 print('files:', files) # 当前路径下所有非目录子文件 file_name('E:/vmware') os.path.splitext() #分离扩展名os.system() #运行shell命令:os.path.exists() #检验给出的路径是否真地存:os.getenv() 与os.putenv() #读取和设置环境变量os.linesep #给出当前平台使用的行终止符 如: windowss使用'\r\n' ,Linux使用'\n'而Mac使用'\r'os.name #指示你正在使用的平台: 如:对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'os.chmod(file) #修改文件权限与时间戳os.exit() #终止当前进程
目录操作:
os.makedirs("file1/file2/file3") #创建文件夹目录. 创建多级目录os.mkdir("file") # 创建文件夹. 但是上级目录必须存在os.copy("oldfile","newfile") #oldfile只能是文件夹,newfile可以是文件,也可以是目标目录os.rename("oldname","newname") #重命名文件(目录) 文件或目录都是使用这条命令os.removedirs() # 删除多级目录, 要求必须是空的os.rmdir("dir") #只能删除空目录 os.listdir() #返回指定目录下的所有文件和目录名os.path.split(path) #返回一个路径的目录名和文件名 os.path.dirname() #获取路径名os.path.basename() #获取文件名os.path.getsize(filename) #获取文件大小os.chdir("path") 换路径
以下为shutil模块 对文件和目录操作
shutil.copytree("olddir","newdir") #复制文件夹: olddir和newdir都只能是目录,且newdir必须不存在shutil.move("oldpos","newpos") #移动文件(目录)
Python文件读写操作
os.remove() #删除文件 或空文件夹os.stat() #获取文件属性with open("abc.txt",mode="w",encoding="utf-8") as f: #写文件,当文件不存在时,就直接创建此文件 passencoding #文件编码 mode #打开模式 name #文件名 关于open 模式:w 以写方式打开,a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)r 以读写模式打开w+ 以读写模式打开 (参见 w )a+ 以读写模式打开 (参见 a )rb 以二进制读模式打开wb 以二进制写模式打开 (参见 w )ab 以二进制追加模式打开 (参见 a )rb+ 以二进制读写模式打开 (参见 r+ )wb+ 以二进制读写模式打开 (参见 w+ )ab+ 以二进制读写模式打开 (参见 a+ )lines = object_file.readlines( ) #读第一行for line in file_object: #如果文件是文本文件,还可以直接遍历文件对象获取每行: print(line)
联系客服