Python3 文件(夹)基本操作

发布时间:2019-10-15 09:05:16编辑:auto阅读(2279)

    相关模块

    基本操作

    • 判断文件(夹)是否存在。
    os.path.exists(pathname)
    # new
    pathlib.Path(pathname).exists()
    • 判断路径名是否为文件。
    os.path.isfile(pathname)
    # new
    pathlib.Path(pathname).is_file()
    • 判断路径名是否为目录。
    os.path.isdir(pathname)
    # new
    pathlib.Path(pathname).is_dir()
    • 创建文件。
    os.mknod(filename)    # Windows下不可用
    open(filename, "w")   # 记得要关闭
    # new
    pathlib.Path(filename).touch(mode=438, exist_ok=True)
    • 复制文件。
    shutil.copyfile("oldfile", "newfile")    # oldfile和newfile都只能是文件,目标文件会被覆盖
    shutil.copy("oldfile", "newfile")        # oldfile只能是文件,newfile可以是文件,也可以是目标目录
    • 删除文件。
    os.remove(filename)
    # new
    pathlib.Path(pathname).unlink()
    • 清空文件。
    file = open("test.txt", w)
    file.seek(0)     
    file.truncate() # 注意文件指针的位置
    file.close()
    • 创建目录。
    os.mkdir(pathname)                # 创建单级目录
    # new
    pathlib.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")     #不能删除非空目录
    # new
    pathlib.Path("dir").rmdir()
    # shutil.rmtree 可以删除非空目录,目录打开时也能删除
    # 约等于'rd /Q /S dir'
    shutil.rmtree("dir")
    • 切换目录
    os.chdir(newpath)
    • open 常用模式。
    'r':  只读(缺省。如果文件不存在,则抛出错误。)
    'w':  只写(如果文件不存在,则自动创建文件。)
    'a':  追加
    'r+': 读写
    • 由全路径名的到路径和文件名
    >>> pathfile = r'D:\abc\def\ghi.txt'
    >>> os.path.dirname(pathfile)
    'D:\\abc\\def'
    # new
    str(Path(pathfile).parent)
    >>> os.path.basename(pathfile)
    'ghi.txt'
    # new
    Path(pathfile).name
    • 获取文件大小
    os.path.getsize(pathfile)    #单位为字节(Byte)
    # or
    os.stat(pathfile).st_size
    # new
    pathlib.Path(pathfile).stat().st_size
    • 获取文件创建/修改/访问时间。
    os.path.getctime(pathfile)    # 创建时间
    os.path.getmtime(pathfile)    # 修改时间
    os.path.getatime(pathfile)    # 访问时间
    # new
    pathlib.Path(pathfile).stat().st_ctime    # 创建时间
    pathlib.Path(pathfile).stat().st_mtime    # 修改时间
    pathlib.Path(pathfile).stat().st_atime    # 访问时间
    • 获取当前文件目录绝对路径
    os.path.abspath('.')
    # new
    str(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'
    # new
     pathlib.Path(r'D:\tmp\3.jpg').suffix
    本文出自 walker snapshot

关键字