zoukankan      html  css  js  c++  java
  • python--005--文件操作(r,w,a)

    1. 文件处理流程:

     1)打开文件,得到文件句柄并赋值给一个变量
    2)通过句柄对文件进行操作(读、写、追加等)
    3)关闭文件

    #========文件处理读操作=========

    ps:文件名为 尘粒.txt
    f=open('尘粒','r',encoding='utf-8')     #python3自动使用utf-8,但是open函数会遵从操作系统的编码
    # data=f.read()   #这个读完后,光标会到最后,再次readline会为空
    # print(data)
    print('第一行',f.readline(),end='')   #end=''加上这个就去掉了最后的换行
    print('第2行',f.readline())
    f.close()
    
    output:
    第一行 hello你好
    第2行 djdhudjddkdkdd
    f=open('尘粒','r',encoding='utf-8')
    data=f.readlines()
    print(data)
    f.close()
    
    output:
    ['hello你好
    ', 'djdhudjddkdkdd
    ', '222
    ', '444
    ', '
    ']


    #========文件处理写操作=========
    注: f.writelines(['777
    ','888
    ',1])   # 文件内容只能是字符串,只能写字符串,这样写会报错
    f=open('尘粒','w',encoding='utf-8')  #使用w会覆盖写
    #f.read()
    f.write('11111
    ')  #注意换行符需要自己加,不会自动加
    f.write('22222
    ')
    f.write('你好
    444
    666
    ')
    print(f.writable())   #是否可写
    # f.writelines(['777
    ','888
    ',1])#文件内容只能是字符串,只能写字符串
    f.close()
    
    output:
    True
    
    尘粒.txt:
    11111
    22222
    你好
    444
    666

    #========文件处理追加操作=========

    f=open('尘粒','a',encoding='utf-8')
    f.write("写到最后")
    f.close()
    
    尘粒.txt:
    11111
    22222
    你好
    444
    666
    写到最后
    
    
    打开文件的模式有:
    r:只读模式
    w:只写模式 (注意会覆盖写)
    a:追加模式
    r+:读写【可读,可写】
    w+:写读【可写,可读】
    a+:

    #==========r+ 读写模式============
    注:r+ 来写文件,文件没有修改,全是覆盖,光标在哪,就从哪里写
    f=open('尘粒','r+',encoding='utf-8')
    f.write("r+模式")
    f.close()
    
    #文件没有修改,全是覆盖,光标在哪,就从哪里写,所以这个例子,会覆盖前面的字符为 r+模式
    
    尘粒.txt:
    r+模式2222
    你好
    444
    666
    写到最后
    
    


    #==========练习============、
    #eg:将源文件修改部分内容后,写入新文件
    src_f=open('尘粒','r',encoding='utf-8')
    data=src_f.readlines()
    src_f.close()
    print(data)
    
    dst_f=open('尘粒','w',encoding='utf-8')
    #dst_f.writelines(data)
    dst_f.write(data[0])
    dst_f.close()
    
    output:
    ['r+模式2222
    ', '你好
    ', '444
    ', '666
    ', '写到最后']
    尘粒.txt:
    r+模式2222
    
    

    #=======with======

    #利用with就可以不用f.close了,系统自动帮忙close
    with open('a.txt','w')as f:
        f.write('11111
    ')
    
    output:
    11111
    
    
    # src_f=open('尘粒','r',encoding='utf-8')
    # dst_f=open('尘粒_new','w',encoding='utf-8')
    #with打开两个文件
    with open('尘粒','r',encoding='gbk')as src_f,
    open('尘粒_new','w',encoding='gbk')as dst_f:
        data=src_f.read()
        dst_f.write(data)
    
    尘粒.txt:
    r+模式2222
    
    尘粒_new.txt:
    r+模式2222


  • 相关阅读:
    wes7配置
    一个很牛逼的工具XueTr
    构造一个好控制一点的长期工作线程
    SmartGit初步使用
    Android开发(一):环境搭建
    zabbix使用短信猫实现报警
    Build Libsvm to dll
    Using OpenCV in VS2012
    My Overlay Icons is Missing
    用Eclipse开发C、C++
  • 原文地址:https://www.cnblogs.com/jinf/p/10926493.html
Copyright © 2011-2022 走看看