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

    复习上节课知识

    一,字符编码

    1,#,coding:“utf-8”:2用来python解释器读取python文件:

    2,Unicode---encode编码----utf-8

    3,utf-8---解码decode-----unicode

    4 python3中ser是以unicode编码形式存放的

    X=‘你好’ x。encode(‘utf-8’)----bytes

    5,bytes类型的用途:

    (1)       存放到文件中 (2)基于网络传输

    二,文件处理

    文件打开模式:r   w   a

    f.read  (读) f.readline(一行一行的读)  f.readlines(全部读出来放列表里)

    f.write (‘11111 22222 ’)  字符串

    f.writelines([‘11 ’,’22222 ’])   可以放列表

    循环:

    For line in f:

    Print(line)

    三,文件处理b模式

    强调: 与t模式类似不能单独使用 必须:rb ,wb,ab

    2,b模式下读写都是以bytes单位的

    3,b模式下一定不能指定encoding参数

    读图片:

    With open(‘1,jpg’,mode=‘rb’)af f:

    Data=f.read()

    Print(data.)  print(type(tata))

    rb转txt

    with open(‘db.txt’,mode=’rb’)as f:

    data=f.read()

    print(data.decode(‘utf-8’))   print(type (data))

    wb txt

    with open(‘b.txt’,mode=’wb’) as f

    msg=’你好’

    f.write (msg.encode(‘utf-8’))

    读写r w

    With open (‘b.txt’,mode=’wb’) as f:

    Data=f.read()

    Print(data.decode(‘utf-8’))#print(type(data))

    操作文件文件t模式只能操作文本文件

    B模式可以处理文本 图片等

    Ab 模式

    With open(‘b.txt’,mode=‘ab’)as f:

    F.write(‘你好’,encode(utf-8))

    循环:

    With open(‘jpg’,mode=‘rb’)as f:

    for line in f:

    print(line)

    文件修改  seek(移动)

    文件修改方法11,先把文件内容全部读入内存,2,然后在内存中完成修改,3,在把修改后的结果覆盖写入原文件

    with open('user.txt',mode='r',encoding='utf-8') as f:
        data=f.read()
        data=data.replace('来','来[第一帅]')

        with open('user,txt',mode='w',encoding='utf-8') as f:
            f.write(data)

    文件修改方法2 以读的方法打开原文件 以写的方法打开一个新文件

    import os

    with open('user.txt',mode='rt',encoding='utf-8') as read_f,
        open('user.txt.swap',mode='wt',encoding='utf-8')as write_f:
        for line in read_f:
            if'来'in line:
                line=line.replace('来','来[fhdfdjfhjhdhf]')

            write_f.write(line)

    os.remove('user.txt')
    os.rename('user.txt.swap','user.txt')

     

     

     

  • 相关阅读:
    angry_birds_again_and_again(2014年山东省第五届ACM大学生程序设计竞赛A题)
    数学入门题目
    POJ1236:Network of Schools(tarjan+缩点)?
    POJ2186:Popular Cows(tarjan+缩点)
    HDU2426:Interesting Housing Problem(还没过,貌似入门题)
    POJ1175:Starry Night(bfs)
    POJ2506:Tiling(递推+大数斐波那契)
    POJ2135:Farm Tour
    POJ2195:Going Home(费用流入门)
    POJ1273:Drainage Ditches(最大流入门 EK,dinic算法)
  • 原文地址:https://www.cnblogs.com/maojiang/p/8635581.html
Copyright © 2011-2022 走看看