码迷,mamicode.com
首页 > 编程语言 > 详细

Python读写文件

时间:2019-12-01 12:00:35      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:lines   nal   final   muti   lease   二进制   ESS   现在   rem   

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 \n by yourself
#write mutiple lines
fout.writelines(theListofLines)
#theListofLines looks like this:
#theListofLines = ["This is 6th line\n", "This is 7th line"]
fout.close()

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

? 如果要追加写的话:

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

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

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

Python读写文件

标签:lines   nal   final   muti   lease   二进制   ESS   现在   rem   

原文地址:https://www.cnblogs.com/jiading/p/11965330.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!