zoukankan      html  css  js  c++  java
  • python基础--文件操作

    文件操作

    目录:
    1.基本概念
    2.基本操作
    3.例子_在磁盘修改文件

    1.基本概念

    三种基本的操作模式 r(只可读) w(只可写) a(追加)
    流程:1 创建文件对象 2 调用文件方法进行操作 3 关闭文件
    注意:必须要有f.close()操作,如果没有close操作数据会缓存,而不是存在磁盘。


    2.基本操作
    (1).read()
    # f=open('小重山','r',encoding='utf8')
    # data=f.read(5)
    # print(data)
    # f.close()

    (2).write()
    # f=open('小重山','w',encoding='utf8')
    # f.write('
    hello world 
    ')
    # f.write('alex')
    # f.close()

    (3).readline()
    # f=open('小重山','w',encoding='utf8')
    # a=f.readline()
    # print(a)
    # f.close()


    (4).readlines()
    # f=open('小重山','w',encoding='utf8')
    #print(f.readlines())
    # f.close()

    (5).tell()
    # f=open('小重山','r',encoding='utf8')
    # print(f.tell())        #  取出光标位置,一个汉字3个字符
    # print(f.read(2))
    # print(f.tell())

    (6).seek()
    # f=open('小重山','r',encoding='utf8')
    # f.seek(0)               # 移动光标到指定的位置
    # print(f.read(4))
    # f.close()

    (7).flush()

    #flush():同步把将数据从缓存转移到磁盘上去

    (8).truncate()
    # f=open('小重山','w',encoding='utf8')
    # f.truncate(5)
    # f.write('hello world')
    # f.truncate(5)
    # f.close()

    (9)r+模式
    # f=open('小重山','r+',encoding='utf8')
    # print(f.tell())
    # print(f.readline())
    # f.close()

    (10)with语句(防止open打开之后忘记关闭文件)
    # with open('小重山', 'r',encoding='utf8') as f:
        # print(f.readline())
        # print(f.read())
    
    

    3.例子_在磁盘修改文件

    # f_read=open('file_1','r',encoding='utf8')
    # f_write = open('file_2','w',encoding='utf8')
    # number = 0
    # for line in f_read:
    #     number += 1
    #     if number == 5:
    #         line = ''.join([line.strip(),'需要添加的内容
    '])
    #     f_write.write(line)
    # f_read.close()
    # f_write.close()
    
    
    
     
  • 相关阅读:
    创建工作窗口
    windows下关闭进程树
    VC socket api使用引入
    实现PC延迟执行函数
    CxImage实现9PNG
    bzoj 3211 花神游历各国
    codevs 3287 货车运输 NOIP2013提高组
    bzoj 3732 Network
    codevs 2370 小机房的树
    图论-最近公共祖先-在线树上倍增
  • 原文地址:https://www.cnblogs.com/Kate-liu/p/9911709.html
Copyright © 2011-2022 走看看