zoukankan      html  css  js  c++  java
  • python3(三十五)file read write

    """ 文件读写 """
    __author__on__ = 'shaozhiqi  2019/9/23'
    
    # !/usr/bin/env python3
    # -*- coding: utf-8 -*-
    
    # 读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符
    f = open('D:/temp/shao.txt', 'r', encoding='UTF-8')
    print(f.read())
    f.close()
    # 执行结果
    # 1.ashahh
    # 2.343erer
    # 文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间能打开的文件数量也是有限的
    
    # ----------------------------------------------------------
    # 反之文件不存在的异常
    try:
        f = open('D:/temp/shao.txt', 'r', encoding='UTF-8')
        print(f.read())
    finally:
        if f:
            f.close()
    
    # -----------------------------------------------------------
    # 简化上述方法
    # 这和前面的try ... finally是一样的,但是代码更佳简洁,并且不必调用f.close()方法。
    with open('D:/temp/shao.txt', 'r', encoding='UTF-8') as f:
        print(f.read())
    
    # 调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,
    # 所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。
    # 另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。
    # 因此,要根据需要决定怎么调用。
    
    # 如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;
    # 如果是配置文件,调用readlines()最方便:
    f = open('D:/temp/shao.txt', 'r', encoding='UTF-8')
    for line in f.readlines():
        print(line.strip())  # 把末尾的'
    '删掉
    
    # ---------------------------------------------------------------------------
    # 二进制文件读取比如图片、视频等。用'rb'模式打开文件即可
    
    fpic = open('D:/temp/截图.PNG', 'rb')
    print(fpic.read())
    fpic.close()
    # b"x89PNG
    x1a
    x00x00x00
    IHDRx00x00x01x15x00x00x00|
    
    # ---------------------------------------------------------------------------------
    # UnicodeDecodeError异常除了设置编码外,还可以设置忽略
    ff = open('D:/temp/shao.txt', 'r', errors='ignore')
    print(ff.read())
    ff.close()
    # ----------------------------------------------------------------------------------------------------------------------
    # 写文件
    ffw = open('D:/temp/shao.txt', 'w', errors='ignore')
    ffw.write('add hello world ')
    ffw.close()
    
    # 查看是否写入成功
    ff = open('D:/temp/shao.txt', 'r', errors='ignore')
    print(ff.read())
    ff.close()
    
    # 1.ashahh
    # 2.343erer
    # add hello world
  • 相关阅读:
    Redis学习
    MySQL索引
    细数 Java 线程池的原理
    红黑树学习
    HashMap学习
    Java集合框架
    Java性能优化的45个细节
    MyBatis理解
    jenkins+git+maven+tomcat+jdk本地部署windows版
    windows版docker安装nginx,并设置目录挂载
  • 原文地址:https://www.cnblogs.com/shaozhiqi/p/11574070.html
Copyright © 2011-2022 走看看