zoukankan      html  css  js  c++  java
  • IO/序列化/JSON

    一.读写文件

    1.open:打开文件

    open(path, mode, encoding='xxx', errors='ignore')


    mode取值:
    rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
    w 以写方式打开,
    a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
    r+ 以读写模式打开,先读后写(注意需要将文件指针重置为0,f.seek(0), 否则将变成追加内容)
    w+ 以读写模式打开 (参见 w ), 先写后读
    a+ 以读写模式打开 (参见 a )
    rb 以二进制读模式打开
    wb 以二进制写模式打开 (参见 w )
    ab 以二进制追加模式打开 (参见 a )
    rb+ 以二进制读写模式打开 (参见 r+ )
    wb+ 以二进制读写模式打开 (参见 w+ )
    ab+ 以二进制读写模式打开 (参见 a+ )

    2.read:读取全部内容

    3.readline:读取一行内容:

    4.readlines:读取所有行,作为列表返回

    5.write:写入内容

    6.writelines:写入序列字符串

    7.close:关闭打开的文件,打开的文件必须及时关闭

    示例代码:

    f = open('a.txt', 'r')
    content = f.read()
    f.close()
    
    print(content)
    

      

    示例代码2:

    f = open('a.txt', 'r')
    content = ''
    for line in f.readlines():
        content += line.strip() #过滤尾部换行符
    f.close()
    
    print(content)
    

      

    示例代码3:

    f = open('a.txt', 'r')
    content = ''
    for line in f.readlines():
        content += line.strip() #过滤尾部换行符
    f.close()
    
    print(content)
    

      

    二.更加简便的方法with

    1.因为读取文件后要关闭,所以一般代码会如下所示:

    content = ''
    try:
        f = open('a.txt', 'r')
        for line in f.readlines():
            content += line.strip() #过滤尾部换行符
    except BaseException:
        pass
    finally:
        f.close()
    
    print(content)
    

      

    2.使用with

    示例代码

    content = ''
    with open('a.txt', 'r') as f:
        for line in f.readlines():
            content += line.strip() #过滤尾部换行符
    print(content)
    

      

    示例代码:

    with open('a.txt', 'a') as f:
        f.writelines(['Hello, world!
    ','Hello, world!
    '])
    

      

    二.内存读写

    1.字符串读写

    借助StrongIO和文件读写大致相同,调用close时,内存释放

    示例:

    from io import StringIO
    
    f = StringIO()
    f.write('hello')
    f.write('word')
    print(f.getvalue())
    f.close()
    

      

    2.字节读写

    借助BytesIO和文件读写大致相同,调用close时,内存释放

    from io import BytesIO
    
    f = BytesIO()
    f.write('你'.encode('utf-8')) #写入经过UTF-8编码的bytes
    f.write('好'.encode('utf-8')) #写入经过UTF-8编码的bytes
    print(f.getvalue())
    f.close()
    

      

    三.操作文件和目录

    1.系统类型:

    >>> import os
    >>> os.name
    'nt'
    

      

    posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统。

    2.环境变量:

    >>> os.environ
    >>> os.environ.get('PATH') #获取其中一项
    

      

    3.目录/路径

    os.path模块中的方法

    >>> os.path.abspath('.') #当前目录绝对路径
    >>> os.path.join(os.path.abspath('.'), 'test') #合并路径
    >>> os.mkdir('ror') #创建目录
    >>> os.rmdir('ror') #删除目录
    >>> os.rename('test.txt', 'test.py') #文件重命名
    >>> os.remove('test.py') #删除文件
    

      

    #拆分路径
    >>> os.path.split('/usr/ror/a.txt')
    ('/usr/ror', 'a.txt')
    
    #拆分扩展名
    >>> os.path.splitext('/usr/ror/a.txt')
    ('/usr/ror/a', '.txt')
    

      

    #列出当前目录下所有的txt文件
    >>> [file for file in os.listdir('.') if os.path.isfile(file) and os.path.splitext(file)[1] == '.txt']
    
    #拷贝文件(拷贝当前目录下a.txt到b.txt)
    >>> import shutil
    >>> shutil.copyfile('a.txt', 'b.txt')
    

      

    四.序列化/反序列化

    1.序列化

    示例代码:

    >>> import pickle
    >>> d=dict(age=10,name='g')
    >>> pickle.dumps(d) #dumps 方法把任意对象序列化成一个bytes
    >>> f=open('a.txt', 'wb')
    >>> pickle.dump(d, f)  #dump()直接把对象序列化后写入一个文件对象
    >>> f.close()
    

      

    2.反序列化

    可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个文件对象中直接反序列化出对象

    >>> f=open('a.txt', 'rb')
    >>> d=pickle.load(f)
    >>> f.close()
    >>> d
    {'age': 10, 'name': 'g'}
    

      

    五.JSON

    1.dict

    >>> import json
    >>> d=dict(age=10,name='g')
    >>> json_str = json.dumps(d) #从字典/对象序列化
    >>> json_str
    '{"age": 10, "name": "guobin"}'
    >>> json.loads(json_str) #从字符串反序列化
    {u'age': 10, u'name': u'guobin'}
    

      

    2.class

    示例代码

    import json
    
    class Foo:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    # json encode obj
    f = Foo('g', 15)
    print(json.dumps(f.__dict__))
    
    #json decode obj
    def hook(d):
        return Foo(d['name'], d['age'])
    f2 = json.loads('{"name": "g", "age": 15}', object_hook= hook)
    print(f2)
    

      

    输出:
    {"name": "g", "age": 15}
    <__main__.Foo object at 0x00000213E383A940>

  • 相关阅读:
    document 对象
    AdodbStream的方法和属性
    WEB开发者版本
    ATI HD2400
    驱蚊植物
    PHP5+UTF8多文件上传类
    nVIDIA_driver
    ati
    Zend_Http_Client setFileUpload
    Sqlserver2005 数据类型
  • 原文地址:https://www.cnblogs.com/itfenqing/p/10261908.html
Copyright © 2011-2022 走看看