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

    复习:

    字符编码表(字符和数字一一对应关系的表)需掌握:

     1、以什么编码存的,就应该以该编码取
            #coding:utf-8 :用于python解释器读取python文件,
             所以文件头指定的编码必须跟python文件存储时用的编码一致

     2、 编码解码
            unicode---编码encode---》utf-8
            utf-8---解码decode---》unicode
            python3中str是以unicode编码形式存放的
            x='你好'
            x.encode('utf-8') ----> bytes
            bytes.decode('utf-8')------------->str(unicode)

     3、bytes类型(可当成二进制的数据, bytes为python3中新的数据类型)的用途:
         1、存放到文件中(bytes类型可以直接扔给硬盘)
         2、基于网络传输

      ## x.encode(‘utf-8’)的结果是一个放在内存中的值

     

    文件处理:
        with open('a.txt', encoding='utf-8') as f1,
                open('b.txt', encoding='utf-8') as f2,
                open('c.txt', encoding='utf-8') as f3:
            pass
    ## +回车 在pycharm中换到下一行,但实际上还是一行

        默认是t模式,t不能单独使用,必须是rt,wt,at

    f.read() 读出来的是一个打的字符串
    f.readlines() 相当于一个for循环
     
    绝对路径与相对路径:
    绝对路径:在任意位置都可以定位该文件
    相对路径:以所在位置为参考定位文件
     
    …py_learnday1	est.py: windows 系统用‘’表示子关系
    …/py_learn/day1/test.py: linux系统用‘/ 表示子关系’
    while True:
        msg="""
        1
    注册
        2 查看
        """
       
    print(msg)
        choice=input('输入编号>>: ').strip()
        if choice == "1":
            print('33[45m注册。。。33[0m')
            phone=input('手机号>>: ').strip()
            name=input('用户名>>: ').strip()
            pwd=input('密码>>: ').strip()
            sex=input('性别>>: ').strip()
            with open('db.txt','at',encoding='utf-8') as f:
                f.write('%s,%s,%s,%s ' %(phone,name,pwd,sex))
        elif choice == '2':
            print('33[44m查看。。。。。33[0m')

            phone=input('请输入你的手机号:').strip()
            with open('db.txt','rt',encoding='utf-8') as f:
                for line in f:
                    if line.startswith(phone):
                        print(line,end='')
                        break
        else
    :
            print('33[43m输入非法编号...33[0m']

    文件处理:

    文件的打开模式b模式
    强调:
    1、与t模式类似不能单独使用,必须是rb,wb,ab
    2、b模式下读写都是以bytes单位的
    3、b模式下一定不能指定encoding参数

    rb模式

    with open('1.jpg',mode='rb',) as f:
        data=f.read()
        print(data,)
        print(type(data))

    with open('db.txt',mode='rb',) as f:
        data=f.read() #
       
    print(data.decode('utf-8')) #bytes-----unicode
       
    print(type(data))

    #‘utf-8’等是字符编码,只能处理字符,处理不了包括图片视频在内的其他形式

    # b模式(二进制)也可以读txt,但要读出字符,需要解码

    wb模式

    with open('b.txt',mode='wb') as f:
        msg='你好啊,吴三炮'
       
    f.write(msg.encode('gbk'))   #在utf-8平台乱码,reload去gbk可读
    with open('b.txt',mode='ab') as f:
        msg='你好啊,吴三炮'
       
    f.write(msg.encode('utf-8'))  #在gbk平台乱码,reload去utf-8可读
    with open('b.txt',mode='rb') as f:
        data=f.read()
        print(type(data))
        print(data.decode('utf-8'))

    with open('1.jpg',mode='rb') as f:
        data=f.read()
        print(type(data))
        print(data.decode('utf-8'))

    ##error, utf-8不能处理非字符类型文件

    ab模式

    with open('b.txt',mode='ab') as f:
        f.write('你好'.encode('utf-8'))

    with open('1.jpg','rb') as f:
        for line in f:
            print(line)
    可读可写 #不改变r/w/a在判断文件存在与否后作出的基本处理方法, 很少用
    #r+t (r+)
    with open('b.txt','r+t',encoding='utf-8') as f:
        print(f.readable())
        print(f.writable())
        print(f.readline())
        f.write(' 吴大炮你也号 ')
    #w+t (w+)
    #a+t (a+)
    #U   :通用换行符,没用

    文件的处理

    with open('db.txt','r+',encoding='utf-8') as f:
    f.seek(9) #偏移量的单位是字节,utf-8中,一个中文字符占三个字节,一个英文字符占一个字节
    print(f.tell())   #9
    print(f.read())
     
    硬盘无删改,只是覆盖。删除后,硬件上的原空间被标定free。可以在内存中删改
    修改文件方式一:
    1、先把文件内容全部读入内存
    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)

    修改文件方式二:
    1、以读的方式打开原文件,以写的方式打开一个新文件
    2、读一行原文内容,写入新文件,如果该行内容是需要修改的内容,那么修改完后再写入新文件
    3、删除原文件,将新文件名重命名为原文件名

    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('吴佩其','吴佩其[老男汉特别特别的老]')
            write_f.write(line)
    os.remove('user.txt')
    os.rename('user.txt.swap','user.txt')

    #总的来说第一种方式耗内存,第二种方式耗硬件

    copy #在终端中运行

    import sys
    l=sys.argv # 把命令行中解释器后空格分割的所有参数都存成列表
    # print(l)

    src_file_path=l[1]
    dst_file_path=l[2]
    # print(src_file_path)
    # print(dst_file_path)
    with open(r'%s' %src_file_path,mode='rb') as src_f,
            open(r'%s' %dst_file_path,mode='wb') as dst_f:
        for line in src_f:
            dst_f.write(line)
  • 相关阅读:
    Python3.x:定义一个类并且调用
    Spring编码过滤器:解决中文乱码
    Web.xml中自动扫描Spring的配置文件及resource时classpath*:与classpath:的区别
    你是否属于中等收入群体
    Python3.x:BeautifulSoup()解析网页内容出现乱码
    Activiti工作流引擎数据库表结构
    Java:出现错误提示(java.sql.SQLException:Value '0000-00-00' can not be represented as java.sql.Date)
    Django框架搭建(windows系统)
    Eclipse配置多个jdk
    Activiti:创建activiti工程
  • 原文地址:https://www.cnblogs.com/zhangyaqian/p/py20180323.html
Copyright © 2011-2022 走看看