zoukankan      html  css  js  c++  java
  • 第五节:文件操作

    read读取文件全部内容,默认就是读模式,所以不需要指定模式:

    f = open('test2.py',encoding='utf8')
    data = f.read()
    print(data)
    f.close()

    redline读取文件的一行内容,打印的时候加上end=''否则会有空格:

    f = open('test2.py',encoding='utf8')
    data = f.readline()
    data1 = f.readline()
    print(data,end='')
    print(data1,end='')
    f.close()

    readlines读取的全部内容,以列表的方式打印每一行,每行就是一个元素

    f = open('test2.py',encoding='utf8')
    data = f.readlines()
    print(data)

    f.close()

    write写如果该文件存在则清空,如果不存在则创建新的文件,文件内容必须是字符串

    f = open('test3.py','w',encoding='utf8')
    f.write("写文件")
    f.close()

    writelines以列表的形式写入,写多行的时候记得加

    f = open('test3.py','w',encoding='utf8')
    f.writelines(["dsad
    ","dsad
    "])
    f.close()

    a追加操作:

    f = open('test3.py','a',encoding='utf8')
    f.writelines(["dsad
    ","dsad
    "])
    f.close()

    r+可读可写的方式打开,写的时候从光标开始的地方开始写

    f = open('test3.py','r+',encoding='utf8')
    print(f.read())
    f.writelines(["dsad
    ","dsad
    "])
    f.close()

    with as同事打开多个文件,不需要close关闭文件,换行

    with open('test3.py','r',encoding='utf8') as f,
            open('test2.py','r',encoding='utf8') as g:
            print(f.read())
            print(g.read())
  • 相关阅读:
    iBatisnet 1.5版本的配置文件的几个变化
    使用Trace时要注意
    无刷新转页面?
    无刷新“页面跳转”问题一:与AtlasToolKit协同工作
    Assembly的Release与Debug
    iBatis.Net系列(四) iBatisNet API基础
    Atlas 调用web service
    无刷新“页面跳转”
    iBatis.Net系列(六) ResultMap
    在GridView中格式化时间字段
  • 原文地址:https://www.cnblogs.com/sxdpython/p/12650723.html
Copyright © 2011-2022 走看看