首页 > 其他分享 >test34-文件输入输出序列化和反序列化 msgpack map用法

test34-文件输入输出序列化和反序列化 msgpack map用法

时间:2022-10-18 03:22:05浏览次数:72  
标签:map msgpack args sys lst print import 序列化

#!/usr/bin/env python
# -*- encoding:utf-8 -*-
'''
import csv
headers=['学号','姓名','分数']
rows=[('202001','张三','98'),
('202002','李四','95'),
('202003','王五','96')]
with open('score.csv','w',encoding='utf8') as f:
writer=csv.writer(f)
writer.writerow(headers)
writer.writerows(rows)

1 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|
import csv
headers=['学号','姓名','分数']
rows=[
{'学号':'2022001','姓名':'张三','分数':'98'},
{'学号':'2022002','姓名':'李四','分数':'95'},
{'学号':'2022003','姓名':'王五','分数':'96'},
]
with open('score1.csv','w',encoding='utf8') as f:
writer=csv.DictWriter(f,headers)
writer.writeheader()
writer.writerows(rows)

2 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import csv
headers=['学号,姓名,分数','\n']
csv=['202001,张三,98','\n',
'202002,李四,95','\n',
'202003,王五,96']
with open('scroe3.csv','w',encoding='utf8') as f:
f.writelines(headers)
f.writelines(csv)

3 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import msgpack
var={
'a':'this',
'b':'is',
'c':'a test',
'd':'alex'
}
with open(r'..\test\data.txt','wb') as f1:
msgpack.dump(var,f1)
with open(r'..\test\data.txt','rb') as f2:
var2=msgpack.load(f2,encoding='utf8')
print(var2)

4 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import json
import msgpack

stu={
'name':'lili',
'age':18,
'score':98
}
msg_str=msgpack.packb(stu)
print(len(msg_str)) #23
json_str=json.dumps(stu)
print(len(json_str)) #40

#反序列化
stu_dict=msgpack.unpackb(msg_str,encoding='utf-8')
print(stu_dict)

5 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|


sys.argv #命令行参数List,第一个元素是程序本身路径
sys.exit(n) #退出程序,正常退出时exit(0)
sys.version #获取Python解释程序的版本信息
sys.maxint # 最大的Int值
sys.path #返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform #返回操作系统平台名称
sys.stdin #输入相关
sys.stdout #输出相关
sys.stderror #错误相关

import msgpack
import sys
print('1',sys.argv)
['D:/djangoPro/sample/马哥asynico/test34-文本输入输出.py']
# print('2',sys.exit(0))

print('3',sys.version)
3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]
# print('4',sys.maxint)
print('5',sys.path)
['D:\\djangoPro\\sample\\马哥asynico', 'D:\\djangoPro\\sample',
'K:\\Program Files\\1\\PyCharm 2020.2.3\\plugins\\python\\helpers\\pycharm_display',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\win32\\lib',
'C:\\Users\\Msi\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages\\Pythonwin',
'K:\\Program Files\\1\\PyCharm 2020.2.3\\plugins\\python\\helpers\\pycharm_matplotlib_backend']
print('6',sys.platform)
6 win32
print('7',sys.stdin)
7 <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
print('8',sys.stdout)
8 <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
# print('9',sys.stderror)

6 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import sys
# for i in sys.argv:
# print(i)
if __name__=="__main__":
for item in sys.argv:
print(item)
# D:/djangoPro/sample/马哥asynico/test34-文本输入输出.py

7 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('echo')
args=parser.parse_args()
print(args)
print(args.echo)
# usage: test34-文本输入输出.py [-h] echo
# test34-文本输入输出.py: error: the following arguments are required: echo


8 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|
import argparse
parser = argparse.ArgumentParser(description = 'this is a description')
# parser.add_argument('--ver', '-v', action = 'store_true', help = 'hahaha')
# required标签就是说--ver参数是必需的,并且类型为int,输入其它类型会报错


# 将变量以标签-值的字典形式存入args字典
args = parser.parse_args()
if args.ver:
print("Ture")
else:
print("False")

9 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import argparse
parser = argparse.ArgumentParser(description = 'this is a description')

# parser.add_argument('--ver', '-v', required = True, type = int)
# args = parser.parse_args()
# if args.ver:
# print("Ture")
# else:
# print("False")
parser.add_argument('file', choices = ['test1', 'test2'])
args = parser.parse_args()
print('read in %s'%(args.file))

# usage: test34-文本输入输出.py [-h] {test1,test2}
# test34-文本输入输出.py: error: the following arguments are required: file

10 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

import pickle
filename=r'..\test\1.txt'
d={'a':1,'b':'abc','c':[1,2,3]}
e=dict(zip('wqs',range(3)))
# print(e)
l=list('123')
i=99
with open(filename,'wb') as f:
pickle.dump(d,f)
pickle.dump(l,f)
pickle.dump(i,f)
pickle.dump(e,f)
with open(filename,'rb') as f:
print(f.read(),f.seek(0))
for _ in range(4):
x=pickle.load(f)
print(type(x),x)

<class 'dict'> {'a': 1, 'b': 'abc', 'c': [1, 2, 3]}
<class 'list'> ['1', '2', '3']
<class 'int'> 99
<class 'dict'> {'w': 0, 'q': 1, 's': 2}

11 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|


import pickle
class AA:
tttt='ABC'
def show(self):
print('abc')
a1=AA()
sr=pickle.dumps(a1)
print('sr={}'.format(sr))

a2=pickle.loads(sr)
print(a2.tttt)
a2.show()
print(id(a1),id(a2))

# sr=b'\x80\x04\x95\x16\x00\x00\x00\x00\x00\x00\x00\x8c\x08__main__\x94\x8c\x02AA\x94\x93\x94)\x81\x94.'
# ABC
# abc
# 1493034614736 1493034614688
12 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

#有一个文件,对其进行单词统计,不区分大小写,并显示单词重复最多的10个单词
d={}
with open('sample.txt',encoding='utf8') as f:
for line in f:
words=line.split()
for word in map(str.lower,words):
d[word]=d.get(word,0)+1
print(sorted(d.items(),key=lambda item:item[1],reverse=True))



13 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|
line=This module implements some useful functions on pathnames.
To read or write files see
# d={}
# words=line.split()
# for word in map(str.lower,words):
# print(word)
# # d[word]=d.get(word,0)+1

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.
注释中翻译为:

map(func, *iterables)——> map对象

创建一个迭代器,使用来自的参数计算函数每个迭代器。当最短的迭代器耗尽时停止。

作用:

map(func, lst) ,将传⼊的函数变量 func 作⽤到 lst 变量的每个元素中,并将结果组成新的列表 (Python2)/ 迭代器(Python3) 返回。

注意:

map()返回的是一个迭代器,直接打印map()的结果是返回的一个对象。

lst=['1','2','3','4','5','6']
print(lst)
lst_int=map(lambda x:int(x),lst)
for i in lst_int:
print(i,end=' ')
print()
print(list(lst_int))

['1', '2', '3', '4', '5', '6']
1 2 3 4 5 6
[]


14 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

list1=[1,2,3,4,5]
list2=[1,2,3,4,5,6]
list3=[1,2,3,4,5,6,7,8]
def func1(x,y,z):
return x+y+z
def func2(x,y,z):
return x,y,z
result1=map(func1,list1,list2,list3)
print(result1)
print(list(result1))
result2=map(func2,list1,list2,list3)
print(result2)
print(list(result2))

# <map object at 0x0000013369CF4EB0>
# [3, 6, 9, 12, 15]
# <map object at 0x0000013369CF4DC0>
# [(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)]

15 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

lst=map(str,[i for i in range(10)])
print(list(lst))
lst_2=map(str,range(5))
print(list(lst_2))

# ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# ['0', '1', '2', '3', '4']


16 |!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|!!|

标签:map,msgpack,args,sys,lst,print,import,序列化
From: https://www.cnblogs.com/mengdie1978/p/16801277.html

相关文章