zoukankan      html  css  js  c++  java
  • 文件处理

    #r模式,默认模式,文件不存在则报错
    # f=open('a.txt',encoding='utf-8')
    # print(f.read())#读全部
    # print(f.readline())#读一行
    # print(f.readlines())#读全部列表形式
    # f.close()#关闭
    #w模式,没有文件则创建一个新文件,存在则覆盖
    # f=open('b.txt','w',encoding='utf-8')
    # f.write()
    # f.writelines()#以列表为单位往里面写
    # f.close()
    #a模式,没有文件则一个新文件,文件存在不会覆盖,写内容是追加的方式写
    # f=open('c.txt','a',encoding='utf-8')
    # f.write()
    # f.close()
    
    #其他方法
    #a模式,没有文件则一个新文件,文件存在不会覆盖,写内容是追加的方式写
    # f=open('a.txt','w',encoding='utf-8')
    # f.write()
    # f.flush()#把内存数据刷到硬盘
    # f.close()
    # print(f.closed)#判断文件是否关闭
    # print(f.name,f.encoding)#查看文件名和字符编码
    # print(f.readable())#判断是否可读
    # print(f.writable())#判断是否可写
    
    
    # f=open('a.txt',encoding='utf-8')
    # print(f.read(3))#读取三个字符
    # f.seek(0)#移动光标到开始位置
    # f.seek(3)#从文件开头移动三个字节
    # print(f.tell())#打印当前光标的位置
    # print(f.truncate(3))#截断文件开始的3个字节
    # f.close()#关闭
    
    # rb
    # f=open('a.txt','rb')
    # f.seek(3,0)#默认是0,从文件开头移动3个字节
    # f.seek(3,1)#从当前位置开始移动3个字节
    # f.seek(-1,2)#从末尾开始移动3个字节
    # print(f.read())#二进制的形式
    # print(f.read().decode('utf-8'))#bytes转unicode
    # f.close()
    
    # wb
    # f=open('d.txt','wb')
    # print(f.write())
    # print('wahaha'.encode('utf-8'))#unicode转bytes
    # f.close()
    
    #修改文件
    # import os
    # read_f=open('a.txt','r',encoding='utf-8')
    # write_f=open('a.txt.swp','w',encoding='utf-8')
    # for line in read_f:
    #     if 'wa' in line:
    #         line=line.replace('wa','ha')
    #     write_f.write(line)
    # read_f.close()
    # write_f.close()
    # os.remove('a.txt')
    # os.rename('a.txt.swp','a.txt')
    #上下文管理with
    # import os
    # with open('a.txt','r',encoding='utf-8') as read_f,
    #     open('a.txt.swp','w',encoding='utf-8') as write_f:
    #     for line in read_f:
    #         if 'wa' in line:
    #             line=line.replace('wa','ha')
    #         write_f.write(line)
    # os.remove('a.txt')
    # os.rename('a.txt.swp','a.txt')
  • 相关阅读:
    51Nod--1247 可能的路径(gcd)
    51Nod--1117 聪明的木匠(排序)
    51Nod--1076 2条不相交的路径(强连通分量)
    HDU--4486 Task(贪心)
    BZOJ--1045-- 糖果传递(中位数,排序)
    [Windows Server 2012] Discuz X3安全设置
    [Windows Server 2012] PHPWind安全设置
    [Windows Server 2012] MySQL安全加固
    [Windows Server 2012] Filezilla安全加固方法
    [Windows Server 2012] WordPress安全设置方法
  • 原文地址:https://www.cnblogs.com/z-x-y/p/7010815.html
Copyright © 2011-2022 走看看