文件操作

操作图片的

f=open('1.jpg','rb')
f1=open('11.jpg','wb')
f1.write(f.read())

r只读

readline()   读取一行,自带\n(换行)
readlines()  读取全部一行一行(没换行)的形式存在放列表里

模式是r的时候 read(3) 就是读取3个字符(数量)
模式是rb的时候 read(3) 就是读取3个字节
Read()全部读取

W只写模式

如果文件不存在就是新建一个
覆盖写,写之前先把文件清空
a 追加写 不能读

文件的末尾写rb 只要是带b的模式,注意的是不能有encoding

光标

seek(0) eek()  移动光标
    0,0    开头
    0,1    当前
    0,2    末尾     单个数 
f.seek(6)  # 字节
seek(3)   移动3个字节,按照我们编码集进行计算的
tell() 查看光标 光标是按照字节数的

truncate() 截取 内容是字节数
r+ #读 写
w+ #写 读 写读的时候是读不到内容的,除非移动光标
a+ #追加 读 不管怎么读都读不到内容,除非移动光标

文件的修改

with open('s','r',encoding='utf-8')as f ,\
open('a.log','a',encoding='utf-8') as f1:
msg = f.read()
msg = msg.replace('alex','ALEX')
f1.write(msg)

python2 将中文写进文件

把unicode转utf8(py2 使用dump和load 不管用,py3可以直接使用dump和load将文字写进文件)

fd = {"cx":"sfdfsddd","sad":"大声道"}
d_d = json.dumps(fd)

def DescribeNodeStatus():
        with open('DescribeNodeStatus.json', 'w') as f:
            f.write(d_d)
        with open('DescribeNodeStatus.json', 'r' ) as f:
            s = f.read().decode('unicode_escape')
            print(s)

posted on 2020-02-25 14:44  xm微微一笑  阅读(101)  评论(0编辑  收藏  举报

导航