美文网首页
python基础库

python基础库

作者: ahqrt | 来源:发表于2020-02-24 15:48 被阅读0次

    1. 文件操作

    path类

    from pathlib import Path
    path = Path("/usr/local/bin")
    # 判断路径是否存在
    path.exists()
    # 判断是否是文件
    path.is_file()
    #判断是否是目录
    path.is_dir()
    # 文件的绝对路径
    path.absolute()
    
    path.name # 返回文件的名字
    path.stem # 返回不带扩展名的文件名
    path.suffix # 返回文件的扩展名
    path.parent # 返回文件的父母路
    
    

    操作目录

    from pathlib import Path
    path = Path("ecommerce")
    path.iterdir() # 返回一个生成器对象
    

    当我们需要处理的文件很多的时候,这样就可以节省一下内存空间

    然后就可以遍历这个生成器进行操作比如

    paths = [p for p in path.iterdir()]
    

    paths里面存的是一个列表,返回的是

    因为我是mac操作系统,所以返回的是PosixPath对象,如果是Windows返回的就是WindowsPath

    paths = [p for p in path.iterdir() if p.is_dir()]
    

    这样得到的就是只有目录的文件夹

    然而这样的方法存在的问题就是没法进行模糊搜索,和递归搜索,所以接下来我们看一种新的方法

    glob 传入的参数是一个格式样本 返回的也是一个生成器

    py_files = [p for p in path.glob("*.py")]
    
    递归搜索
    py_files = [p for p in path.rglob("*.py")]
    

    这样我们得到的就是ecommerce目录以及子目录下面所有的py文件

    文件操作

    path = Path("ecommerce/__init__.py")
    path.exists()
    path.rename("init.txt") # 重命名
    path.unlink() # 删除
    path.stat() # 返回文件的属性信息
    
    stat()的返回值
    从文件中读取数据
    path.read_bytes() # 以字节形式读取
    path.read_text() # 返回字符串结果
    path.write_text("...") # 写文件
    # 复制    
    source = Paht("ecommerce/__init__.py")
    target = Path()/"__init.py"
    target.write_text(source.read_text())
    
    

    然而上面的复制方法有一些奇怪,我们还有更好的方法,let's go

    有一个shutil或者shell utilities的类,专门针对肤质移动文件的专属方法

    import shutil
    source = Paht("ecommerce/__init__.py")
    target = Path()/"__init.py"
    shutil.copy(source, target)
    

    这样,比起来用path对象就清楚多了

    处理压缩文件

    from pathlib import Path
    from zipfile import ZipFile
    # 写入
    zip = ZipFile("files.zip", "w")
    for path in Path("ecommerce").rglob("*.*"):
            zip.write(path)
    zip.close()
    # 解压
    zip.extractall("里面传入要解压的目录名")
    
    

    csv文件处理

    import csv
    # 写入csv文件
    with open("data.csv", "w") as file:
        writer = csv.writer(file)
        # 写入表头
        writer.writerow(["transaction_id", "product_id", "price_id"])
        # 写入数据
        writer.writerow([1000, 1, 5])
        
    # 读取csv文件中的数据
    with open("data.csv") as file:
        reader = csv.reader(file) # 可遍历
        print(list(reader))
    

    注意reader对象是有一个位置序号的,当你第一次遍历结束以后,他就到了文件末尾了

    处理json文件

    json作为一种很常用的数据接口,我们需要了解一些基本的用法

    import json
    from pathlib import Path
    
    # json 文件格式
    mivies = [
      {"id": 1, "title":"hello world", :"year":1879},
      {"id": 2, "title":"hello world22222", :"year":1879},
    ]
    
    data = json.dumps(movies)
    # 写入文件
    Path("movies.json").write_text(data)
    
    # 读取文件
    data = Path("movies.json").read_text()
    movies = json.loads(data)
    

    相关文章

      网友评论

          本文标题:python基础库

          本文链接:https://www.haomeiwen.com/subject/loivqhtx.html