文件操作-序列化json-pickle-yaml

Terminal 终端

>>> path = os.path.join(current_path,'aa.txt')
>>> f = open(path,'w')
>>> f.write('你好呀~')
4
>>> f.close()
>>> f = open(path,'w+')
>>> f.write('再见,测试~')
6
>>> f.close()
>>> f = open(path,'w')
>>> f.write('hhhhhhh')
7
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
io.UnsupportedOperation: not readable
>>> f.close()

- 有+号代表可以读取;没有,就是只能写入,不能读取
>>> f = open(path,'w+')
>>> f.write('wwwww++++')
9
>>> f.read()   # 开始的时候在最后一位,所以读取为空字符串,调整索引位置
''
>>> f.seek(0)    # + 可以读取文件,调整读取索引位置seek(0)
0
>>> f.read()
'wwwww++++'
>>> f.close()
>>> f = open(path,'ab')
>>> f.write('欢迎来到beijing')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
>>> f.write(b'欢迎来到beijing')
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> message = b'欢迎来到beijing'
  File "<stdin>", line 1
SyntaxError: bytes can only contain ASCII literal characters.
>>> message = '欢迎来到beijing'
>>> mess_b = message.encode('utf-8')
>>> f.write(mess_b)
19
>>> mess_b
b'\xe6\xac\xa2\xe8\xbf\x8e\xe6\x9d\xa5\xe5\x88\xb0beijing'
>>> f.close()

>>> f = open(path,'a+')
>>> f.write('test1\n')
6
>>> f.write('test2\n')
6
>>> f.write('test3\n')
6
>>> f.close()
>>> f = open(path,'a')
>>> l = ['今天天气很晴朗','你好吗?','我喜欢你']
  File "<stdin>", line 1
    l = ['今天天气很晴朗','你好吗?','我喜欢你']
                  ^
SyntaxError: invalid character in identifier
>>> l = ['今天天气很晴朗','你好吗?','我喜欢你']
>>> f.writelines(l)
>>> f.close()
>>> f = open(path,'a')
>>> l = ['今天天气很晴朗\n','你好吗?\n','我喜欢你']
>>> f.writelines(l)
>>> f.close()

用pycharm重写

import os.path

def creat_package(path):
    if os.path.exists(path):
        raise Exception('{} 已存在,不能创建'.format(path))
    else:
        os.makedirs(path)
    init_path = os.path.join(path,'__init__.py')
    f = open(init_path,'w')
    f.write('# coding:utf-8 \n')
    f.close()


# 添加自动换行功能
class Open(object):
    def __init__(self,path,mode='w',is_return= True):
        self.path = path
        self.mode = mode
        self.is_return = is_return

    def write(self,message):
        f = open(self.path, mode=self.mode)
        if self.is_return:
            if message.endswith('\n'):
                message = message
            else:
                message = '%s\n' % message
        try:
            f.write(message)
        except Exception as e:
            print(e)
        finally:
            f.close()

if __name__ == '__main__':
    current_path = os.getcwd()
    # path = os.path.join(current_path,'test1')
    # creat_package(path)
    open_path = os.path.join(current_path,'aaa.txt')
    o = Open(open_path)
    # o.write('你好,上海')
    o.write('我喜欢你lioiol\n')

Terminal终端体验,f.read(),f.readlines(),f.readline(),f.closed,f.mode,f.name

去掉'\n',删除空行,返回_data列表

In [30]: for i in data:
    ...:     temp = i.strip()
    ...:     if temp != '':
    ...:         _data.append(temp)

==================================================

In [12]: f = open('one_rev.py','r')

In [13]: data = f.read()

In [14]: f.close()

In [15]: data
Out[15]: "# 第一种方法,使用内置函数reversed(seq),反转一个序列对象\na =nprint(list(a))\na1 = reversed(a)\nprint(a1)\nprint(list(a1))\n# reverse 列表\ntest_list = ['A',3,7,'B','C']\nrl = list(reversed(test_list))\nint(rl)\n# reverse 字符串\ntest_string = 'hi~, nice to meet you'\nrs = ersed(test_string)\nprint(rs)\nprint(list(rs))\nprint(rs)\nprint(list(rs))\nrs2 = ''.join(rs)\nprint(rs2)\n\ndef test():\n    print('test-import')\n"

In [16]: print(data)
# 第一种方法,使用内置函数reversed(seq),反转一个序列对象
a = range(5)
print(a)
print(list(a))
a1 = reversed(a)
print(a1)
print(list(a1))
# reverse 列表
test_list = ['A',3,7,'B','C']
rl = list(reversed(test_list))
print(rl)
# reverse 字符串
test_string = 'hi~, nice to meet you'
rs = reversed(test_string)
print(rs)
print(list(rs))
print(rs)
print(list(rs))
rs2 = ''.join(rs)
print(rs2)

def test():
    print('test-import')


In [17]: type(data)
Out[17]: str

In [18]: len(data)
Out[18]: 399

In [19]: f = open('one_rev.py','r')

In [20]: data = f.readlines()

In [21]: f.close()

In [22]: data
Out[22]: 
['# 第一种方法,使用内置函数reversed(seq),反转一个序列对象\n',
 'a = range(5)\n',
 'print(a)\n',
 'print(list(a))\n',
 'a1 = reversed(a)\n',
 'print(a1)\n',
 'print(list(a1))\n',
 '# reverse 列表\n',
 "test_list = ['A',3,7,'B','C']\n",
 'rl = list(reversed(test_list))\n',
 'print(rl)\n',
 '# reverse 字符串\n',
 "test_string = 'hi~, nice to meet you'\n",
 'rs = reversed(test_string)\n',
 'print(rs)\n',
 'print(list(rs))\n',
 'print(rs)\n',
 'print(list(rs))\n',
 "rs2 = ''.join(rs)\n",
 'print(rs2)\n',
 '\n',
 'def test():\n',
 "    print('test-import')\n"]

In [23]: type(data)
Out[23]: list

In [24]: for i in data:
    ...:     print(i)
    ...: 
# 第一种方法,使用内置函数reversed(seq),反转一个序列对象

a = range(5)

print(a)

print(list(a))

a1 = reversed(a)

print(a1)

print(list(a1))

# reverse 列表

test_list = ['A',3,7,'B','C']

rl = list(reversed(test_list))

print(rl)

# reverse 字符串

test_string = 'hi~, nice to meet you'

rs = reversed(test_string)

print(rs)

print(list(rs))

print(rs)

print(list(rs))

rs2 = ''.join(rs)

print(rs2)

def test():

    print('test-import')


In [25]: _data = []

In [26]: for i in data:
    ...:     temp = 1.strip()
  Input In [26]
    temp = 1.strip()
             ^
SyntaxError: invalid syntax


In [27]: for i in data:
    ...:     temp = i.strip()
    ...:     _data.append(temp)
    ...: 

In [28]: 

In [28]: _data
Out[28]: 
['# 第一种方法,使用内置函数reversed(seq),反转一个序列对象',
 'a = range(5)',
 'print(a)',
 'print(list(a))',
 'a1 = reversed(a)',
 'print(a1)',
 'print(list(a1))',
 '# reverse 列表',
 "test_list = ['A',3,7,'B','C']",
 'rl = list(reversed(test_list))',
 'print(rl)',
 '# reverse 字符串',
 "test_string = 'hi~, nice to meet you'",
 'rs = reversed(test_string)',
 'print(rs)',
 'print(list(rs))',
 'print(rs)',
 'print(list(rs))',
 "rs2 = ''.join(rs)",
 'print(rs2)',
 '',
 'def test():',
 "print('test-import')"]

In [29]: _data = []

In [30]: for i in data:
    ...:     temp = i.strip()
    ...:     if temp != '':
    ...:         _data.append(temp)
    ...: 

In [31]: _data
Out[31]: 
['# 第一种方法,使用内置函数reversed(seq),反转一个序列对象',
 'a = range(5)',
 'print(a)',
 'print(list(a))',
 'a1 = reversed(a)',
 'print(a1)',
 'print(list(a1))',
 '# reverse 列表',
 "test_list = ['A',3,7,'B','C']",
 'rl = list(reversed(test_list))',
 'print(rl)',
 '# reverse 字符串',
 "test_string = 'hi~, nice to meet you'",
 'rs = reversed(test_string)',
 'print(rs)',
 'print(list(rs))',
 'print(rs)',
 'print(list(rs))',
 "rs2 = ''.join(rs)",
 'print(rs2)',
 'def test():',
 "print('test-import')"]

In [32]: f = open('one_rev.py','r')

In [33]: data = f.readline()

In [34]: data
Out[34]: '# 第一种方法,使用内置函数reversed(seq),反转一个序列对象\n'

In [35]: data = f.readline()

In [36]: data
Out[36]: 'a = range(5)\n'

In [37]: f.closed
Out[37]: False

In [38]: f.name
Out[38]: 'one_rev.py'

In [39]: f.mode
Out[39]: 'r'

In [40]: f.close()

In [41]: f.closed
Out[41]: True
 

In [42]: import json

In [43]: one = 123

In [44]: two = 'str'

In [45]: three = [1,2,3]

In [46]: four = (9,8,7)

In [47]: five = {'name':'mark'}

In [48]: one_json = json.dumps(one)

In [49]: one_json
Out[49]: '123'

In [50]: type(one_json)
Out[50]: str

In [51]: two_json = json.dumps(two)

In [52]: two_json
Out[52]: '"str"'

In [53]: three_json = json.dumps(three)

In [54]: three_json
Out[54]: '[1, 2, 3]'

In [55]: four_json = json.dumps(four)

In [56]: four_json
Out[56]: '[9, 8, 7]'

In [57]: five_json = json.dumps(five)

In [58]: five_json
Out[58]: '{"name": "mark"}'

In [59]: print(json.loads(one_json),one)
123 123

In [60]: print(json.loads(two_json),two)
str str

In [61]: print(json.loads(three_json),three)
[1, 2, 3] [1, 2, 3]

In [62]: print(json.loads(four_json),four)
[9, 8, 7] (9, 8, 7)

In [63]: print(json.loads(five_json),five)
{'name': 'mark'} {'name': 'mark'}

In [64]: print(json.dumps(True),json.dumps(False))
true false

In [65]: print(json.loads(json.dumps(True)),json.loads(json.dumps(False
    ...: )))
True False

In [66]: print(json.dumps(None))
null

In [67]: print(json.loads(json.dumps(None)))
None

In [68]: import pickle

In [69]: pickle.dumps(five)
Out[69]: b'\x80\x04\x95\x12\x00\x00\x00\x00\x00\x00\x00}\x94\x8c\x04name\x94\x8c\x04mark\x94s.'

In [70]: pickle.loads(pickle.dumps(five))
Out[70]: {'name': 'mark'}

- Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。

- 注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

- 序列化:对象信息/数据结构信息,转化为字符串

- 可以序列化的数据类型:数字,字符,列表,元组,字典

- 序列化json模块:json.dumps(obj)对象序列化为字符串;json.loads(字符串) 字符串反序列化为原始数据类型

import json

def read(path):
    with open(path,'r') as f:
        data = f.read()
        _data = json.loads(data)
    return _data

def write(path,data):
    with open(path,'w') as f:
        if isinstance(data,dict):
            _data = json.dumps(data)
            f.write(_data)
        else:
            raise TypeError('data need dict')
    return True

data = {'name':'小云','age':18,'top':178}

if __name__ == '__main__':
    # write('test.json',data)
    result = read('test.json')
    print(result,type(result))
    result['sex'] = '男'
    write('test.json',result)

- yaml文件使用:文本文件,服务配置文件:key-value,列表,字典

- yaml 5.1之后的版本,新的写法:yaml.load(file,Loader=yaml.FullLoader)

import yaml

def read(path):
    with open(path,'r') as f:
        data = f.read()
    result = yaml.load(data,Loader=yaml.FullLoader)
    return result

if __name__ == '__main__':
    result = read('test_y.yaml')
    print(result)
    print(type(result))
    print(dir(yaml))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值