• 09-python--file


    '''
    open内置函数,调用的是操作系统的接口
    f1变量:文件句柄,对文件的任何操作都得通过文件句柄进行
    encoding:可以不写,默认编码:操作系统的默认编码
    windows:gbk
    linux/mac:utf-8
    '''
    '''
    1、打开文件
    2、操作文件句柄
    3、关闭文件
    '''
    #
    # read
    '''
    f1 = open('gpg.txt')
    content = f1.read() # 全部读
    content = f1.read(7) # 按照字符读
    content = f1.readline() # 按行读
    content = f1.readlines() # 返回一个列表,列表中的每个元素是列表中的每一行
    print(content)
    f1.close()

    for 读取
    f = open('gpg.txt')
    for line in f:
    print(line)
    f.close()

    rb:操作的是非文本的文件,图片、视频、音频
    f = open('ggg.png', mode='rb')
    content = f.read()
    print(content)
    f.close()

    # r+:读并追加
    f = open('rjia.txt', encoding='utf-8', mode='r+')
    content = f.read()
    print(content)
    f.write('sd')
    f.close()
    '''

    # write:如果文件存在,先清空文件内容,再写入
    '''
    f = open('ggg.txt', mode='w', encoding='utf-8')
    f.write('你好')
    f.close()

    # wb
    f1 = open('ggg.png', mode='rb')
    content = f1.read()
    f1.close()

    f2 = open('gggg.png', mode='wb')
    f2.write(content)
    f2.close()
    '''

    # append:有文件在原文件后追加,没有则创建
    # f = open('333.txt', mode='a', encoding='utf-8')
    # f.write('hello ')
    # f.close()

    # tell:光标位置,按字节
    # f = open('rjia.txt', encoding='utf-8')
    # print(f.tell())
    # content = f.read()
    # print(f.tell())
    # f.close()

    # seek:调整光标位置
    # f = open('rjia.txt', encoding='utf-8')
    # print(f.seek(4))
    # content = f.read()
    # print(content)
    # f.close()

    # flush:强制刷新
    # f = open('rjia.txt', encoding='utf-8', mode='w')
    # f.write('asdasdasd')
    # f.flush()
    # f.close()

    # with open('333.txt', encoding='utf-8') as f1:
    # print(f1.read())

    # with open('333.txt', encoding='utf-8') as f1,
    # open('rjia.txt', encoding='utf-8',mode='w') as f2:
    # print(f1.read())
    # f2.write('dffsd')

    '''
    文件修改步骤:
    1、以读的模式打开源文件
    2、以写的模式创建一个新文件
    3、将源文件的内容读取并修改成你想要的新内容,并写入新文件
    4、将源文件删除
    5、将新文件重命名成源文件
    '''

    # import os
    # with open('333.txt', encoding='utf-8') as f1,
    # open('333bak.txt', encoding='utf-8',mode='w') as f2:
    # old_content = f1.read()
    # new_content = old_content.replace('hello', 'dfl')
    # f2.write(new_content)
    # os.remove('333.txt')
    # os.rename('333bak.txt', '333.txt')

    # import os
    # with open('333.txt', encoding='utf-8') as f1,
    # open('333bak.txt', encoding='utf-8',mode='w') as f2:
    # for line in f1:
    # # old_line = line.strip()
    # new_line = line.replace('dfl', 'bbbbb')
    # f2.write(new_line)
    # os.remove('333.txt')
    # os.rename('333bak.txt', '333.txt')
  • 相关阅读:
    Java 环境搭建的一些问题
    DefaultHttpClient is deprecated 【Api 弃用]】
    Java良葛格 学习笔记《二》
    Java良葛格 学习笔记
    JAVA EE 运行环境配置(包含JAVA SE)
    AIR使用文件对象操作文件和目录
    As3.0 类的【枚举】
    Java&&As3.0 中的final 关键字
    字符串参数组合
    PHP 超级全局变量
  • 原文地址:https://www.cnblogs.com/Daspig/p/12793247.html
Copyright © 2020-2023  润新知