zoukankan      html  css  js  c++  java
  • Python读写文件

    Python读写文件

    现在做CV又要开始用Python了,复习一下Python怎么读写文件23333

    1. 读文件

      fin=open('<the address of file>','r')
      #read the whole file
      theWholeFile=fin.read()
      #read a line
      aLine=fin.readline()
      fin.close()
      

      如果要按字节读的话:

      fin=open('<the address of file>','rb')
      try:
          while True:
              certainBytes=fin.read(20)#read 20 Bytes one time
              if not certainBytes:#如果读完了的话
                  break
      finally:
          fin.close()
      
    2. 写文件

    fout=open("<the address of file>",'w')
    #wirte the whole text
    fout.write(theWholeText)#remember if you want to write mutiple lines,please add 
     by yourself
    #write mutiple lines
    fout.writelines(theListofLines)
    #theListofLines looks like this:
    #theListofLines = ["This is 6th line
    ", "This is 7th line"]
    fout.close()
    

    写文件时候没有writeline方法,其实write手动在末尾加上换行符的话就是writeline,或者writekines的列表中只有一个元素也是

    ​ 如果要追加写的话:

    fout=open("<the address of file>",'w+')
    

    如果要写二进制文件的话:

    fout=open("<the address of file>",'wb')
    
  • 相关阅读:
    截取字符串的值
    Tomcat发布项目方法
    struts标签
    正则表达式范例
    树的操作方法
    树结点动态帮定事件
    I/O 流和对象序列化
    Word中的字体大小
    script实现的日期表示
    JavaScript弹出窗口技巧
  • 原文地址:https://www.cnblogs.com/jiading/p/11965330.html
Copyright © 2011-2022 走看看