zoukankan      html  css  js  c++  java
  • python基础day2-文件处理,2019-6-25

    '''
    '''

    '''
    文件处理:
    open()

    写文件
    wt: 写文本

    读文件
    rt: 读文本

    追加写文件
    at: 追加文本

    注意: 必须指定字符编码,以什么方式写
    就得以什么方式打开。 如: utf-8

    执行python文件的过程:
    1.先启动python解释器,加载到内存中。
    2.把写好的python文件加载到解释器中。
    3.检测python语法,执行代码。
    SyntaxError: 语法错误!

    打开文件会产生两种资源:
    1.python程序
    2.操作系统打开文件
    '''

    # 写文本文件
    # 参数一: 文件的绝对路径
    # 参数二: mode 操作文件的模式
    # 参数三: encoding 指定的字符编码
    f = open('file5.txt', mode='w', encoding='utf-8')
    f.write('tankk')
    f.close() # 关闭操作系统文件资源


    # 读文本文件 r == rt
    # f = open('file.txt', 'r', encoding='utf-8')
    # print(f.read())
    # f.close()
    #
    #
    # # 追加写文本文件
    # a = open('file.txt', 'a', encoding='utf-8')
    # a.write(' 合肥学院')
    # a.close()



    '''
    文件处理之 上下文管理.
    with open() as f "句柄"
    '''
    # 写
    # with open('file1.txt', 'w', encoding='utf-8') as f:
    # f.write('墨菲定律')
    #
    # # 读
    # with open('file1.txt', 'r', encoding='utf-8') as f:
    # res = f.read()
    # print(res)
    #
    # # 追加
    # with open('file1.txt', 'a', encoding='utf-8') as f:
    # f.write('围城')
    # # f.close()



    '''
    对图片、音频、视频读写
    rb模式,读取二进制,不需要指定字符编码
    '''

    # 读取相片cxk.jpg
    with open('cxk.jpg', 'rb') as f:
    res = f.read()
    print(res)

    jpg = res

    # 把cxk.jpg的二进制流写入cxk_copy.jpg文件中
    with open('cxk_copy1.jpg', 'wb') as f_w:
    f_w.write(jpg)


    '''
    with 管理多个文件
    '''
    # 通过with来管理open打开的两个文件句柄f_r,f_w
    with open('cxk.jpg', 'rb') as f_r, open('cxk_copy2.jpg', 'wb') as f_w:
    # 通过f_r句柄把图片的二进制流读取出来
    res = f_r.read()
    # 通过f_w句柄把图片的二进制流写入cxk_copy.jpg文件中
    f_w.write(res)

    会当凌绝顶,一览众山小
  • 相关阅读:
    ORACLE 变量定义
    AcWing1082 数字游戏(数位dp)
    AcWing1081 度的数量(数位dp)
    UCF Local Programming Contest 2017 I题 Rotating Cards(贪心+树状数组)
    AcWing1048 鸡蛋的硬度(浅谈两种解法的思考方向)
    CF713C Sonya and Problem Wihtout a Legend (经典dp)
    CF269B Greenhouse Effect (dp LIS)
    CF463D Gargari and Permutations (LCS)
    AcWing987 最长公共子序列
    CF721C Journey (dp+拓扑)
  • 原文地址:https://www.cnblogs.com/leyzzz/p/11087077.html
Copyright © 2011-2022 走看看