zoukankan      html  css  js  c++  java
  • python中文件操作的其他方法

    前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭。本文中介绍下python中关于文件操作的其他比较常用的一些方法。

    首先创建一个文件poems:

    p=open('poems','r',encoding='utf-8')
    for i in p:
    print(i) 或者是
    with open('poems','r+',encoding='utf-8') as f:
      for i in p:
      print(i)
     


    结果如下:
    hello,everyone
    白日依山尽,
    黄河入海流。
    欲穷千里目,
    更上一层楼。

    1.readline   #读取一行内容

    p=open('poems','r',encoding='utf-8')
    print(p.readline())

    print(p.readline())

    结果如下:
    hello,everyone


    白日依山尽,

    #这里的两个换行符,一个是everyone后边的 ,
    一个是print自带的换行

    2.readlines   #读取多行内容

    p=open('poems','r',encoding='utf-8')
    print(p.readlines())  #打印全部内容
    结果如下:
    ['hello,everyone ', '白日依山尽, ', '黄河入海流。 ', '欲穷千里目, ', '更上一层楼。']
    p=open('poems','r',encoding='utf-8')
    for i in p.readlines()[0:3]:
    print(i.strip()) #循环打印前三行内容,去除换行和空格
    结果如下:
    hello,world
    白日依山尽,
    黄河入海流。


    3.tell #显示当前光标位置
    p=open('poems','r',encoding='utf-8')
    print(p.tell())
    print(p.read(6))
    print(p.tell())

    结果如下:
    0
    hello,
    6
    4.seek #可以自定义光标位置
    p=open('poems','r',encoding='utf-8')
    print(p.tell())
    print(p.read(6))
    print(p.tell())
    print(p.read(6))
    p.seek(0)
    print(p.read(6))


    结果如下:
    0
    hello,
    6
    everyo
    hello,
    5.flush
    #提前把文件从内存缓冲区强制刷新到硬盘中,同时清空缓冲区。
    p=open('poems1','w',encoding='utf-8')
    p.write('hello.world')
    p.flush()
    p.close()

    #在close之前提前把文件写入硬盘,一般情况下,文件关闭后
    会自动刷新到硬盘中,但有时你需要在关闭前刷新到硬盘中,这时就可以使用 flush() 方法。
    6.truncate #保留
    p=open('poems','a',encoding='utf-8')
    p.truncate(5)
    p.write('tom')
    结果如下:
    hellotom
    #保留文件poems的前五个字符,后边内容清空,再加上tom


    
    







     
     
     
  • 相关阅读:
    Vue组件以及组件之间的通信
    VueRouter和Vue生命周期(钩子函数)
    Vuex、axios以及跨域请求处理
    element-ui和npm、webpack、vue-cli搭建Vue项目
    2018PyCharm激活方法
    pycharm修改选中字体颜色
    为自己的博客园添加目录锚点和返回顶部
    python初识
    JAVA判断当前日期是节假日还是工作日
    springmvc使用freemarker
  • 原文地址:https://www.cnblogs.com/bianhao89757/p/10192453.html
Copyright © 2011-2022 走看看