这篇文章记录廖雪峰python教程的习题(九)
2018-02-27 21:58
645 查看
IO编程
文件读写
之前接触过 这里就不赘述了,直接上代码:# -*- coding: utf-8 -*- """ Created on Tue Feb 27 13:38:02 2018 @author: xuanxuan """ #open a file ''' def main(): file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') print(file.read()) main() ''' #打开文件需要进行关闭,一种方法是使用try...finally... 另外一种方法是使用with...open...as ''' def main(): try: file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') print(file.read()) finally: file.close() main() ''' #使用with和try...finally效果是一样的 但是代码更简单 而且不用写close()函数 ''' def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') as file: print(file.read()) main() ''' #下面熟悉一下readlines()函数的用法 ''' def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') as file: for line in file.readlines(): #readlines()函数会读取文件的全部内容 存成一个list列表,每一行是list的一个元素 #print(line.strip()) #strip()函数去掉尾部\n print(line) main() ''' #下面熟悉一下readline()函数的用法 ''' def main(): file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') for i in range(3): print(file.readline()) file.close() main() ''' #上面都是打开文本文件,如果是打开二进制文件,只需要'rb'即可 ''' def main(): file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/cat.jpg",'rb') print(file.read()) file.close() main() ''' #另外就是如果是写入其他的编码格式的文件 可以使用open()函数的encoding参数设为对应的编码即可 ''' def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r',encoding='gbk') as file: print(file.read()) main() ''' #如果是文本中混入了其他类型的编码格式 就会出现UnicodeEncodeError 只需要通过open()函数的errors参数传入值ignore 也就是直接忽略相关错误即可 ''' def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r',encoding='gbk',errors='ignore') as file: print(file.read()) main() ''' #当我们需要像磁盘中写入文件时;必须得等到打开的文件关闭之后才可能看到文件中的内容变化情况 ''' def main(): file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan2.txt",'w') file.write("哈哈哈,我就是试一下往磁盘中写入数据的操作!") file.close() #当使用write操作时一定要注意写完之后需要把文件关闭,否则是看不到数据的 main() ''' #使用with 代码更简单 且不需要再写close ''' def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan2.txt",'w') as file: file.write("I just try it !") main() ''' #其实你会发现使用w的方式往磁盘中写入数据时 后一次的操作会覆盖掉前一次的操作,因此我们需要使用追加的方式:a def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan2.txt",'a') as file: file.write("注意啦,我是追加部分!") main()
下面附上一个习题:
“请将本地一个文本文件读为一个str并打印出来:”
def main(): with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan3.txt") as file: s=file.read() print(s) main()
StringIO 和BytesIO
首先使用StringIO 有两种模式:第一种是StringIO()无参数 直接用write写进去 再用getvalue()读取str;另外一种就是使用StringIO()里面有str内容然后使用readline()对函数内容进行读取>>> from io import StringIO >>> file=StringIO() >>> file.write("好好学习") 4 >>> file.write("天天向上") 4 >>> file.getvalue() '好好学习天天向上' >>>
>>> from io import StringIO >>> file=StringIO("好好学习\n天天向上\n加油噻!") >>> while True: ... content=file.readline() ... if content=='': ... break ... print(content) #如果不想输出结果之间的空格太大可以使用content.strip()函数去除尾部\n ... 好好学习 天天向上 加油噻! >>>
>>> from io import StringIO >>> file=StringIO("hello\nworld\nhello\nxuanxuan") >>> for line in file.readlines(): ... print(line.strip()) ... hello world hello xuanxuan
>>> from io import BytesIO >>> file=BytesIO() #首先创建一个BytesIO()再写入 >>> file.write("哈哈".encode('utf-8')) 6 >>> file.getvalue() #getvalue()方法得到值 b'\xe5\x93\x88\xe5\x93\x88'
from io import BytesIO >>> file=BytesIO(b'\xe7\x92\x87\xe7\x92\x87') #也可以先用一个bytes初始化BytesIO然后再像文件一样读取 >>> file.read() b'\xe7\x92\x87\xe7\x92\x87' >>>
>>> from io import StringIO >>> file=StringIO("璇璇\n是一个\n好孩子!\n") >>> for line in file.readlines(): ... print(line.strip()) ... 璇璇 是一个 好孩子! >>> >>> from io import StringIO >>> file=StringIO("璇璇\n是一个\n好孩子!") >>> file.read() '璇璇\n是一个\n好孩子!' >>> >>> from io import StringIO >>> file=StringIO("璇璇\n是一个\n好孩子!") >>> while True: ... content=file.readline() ... if content=='': ... break ... print(content.strip()) ... 璇璇 是一个 好孩子!
序列化
发现我看不懂了,哦多剋,,、直接上一段代码:
>>> >>> import pickle >>> d=dict(name='xuanxuan',age=22,score=100) >>> pickle.dumps(d) b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x08\x00\x00\x00xuanxuanq\x02X\x03\x00\x00\x00ageq\x03K\x16X\x05\x00\x00\x00scoreq\x04Kdu.' >>> >>> >>> import pickle >>> d=dict(name='xuanxuan',age=20,score=100) >>> file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan5.txt",'wb') >>> pickle.dump(d,file) >>> file.close() >>> >>> >>> file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan5.txt",'rb') >>> data=pickle.load(file) >>> data {'name': 'xuanxuan', 'age': 20, 'score': 100} >>>
json
>>> import json >>> d=dict(name='xuanxuan',age=22,score=100) #dict对象可以使用json.dumps转换成字符串 >>> json.dumps(d) '{"name": "xuanxuan", "age": 22, "score": 100}'
>> import json >>> json_str='{"name": "xuanxuan", "age": 22, "score": 100}' >>> d=json.loads(json_str) >>> d {'name': 'xuanxuan', 'age': 22, 'score': 100}
#如果不是一个dict对象,而是一个class对象 >>> >>> class Student(object): ... def __init__(self,name,age,score): ... self.name=name ... self.score=score ... self.age=age ... >>> s=Student('xuanxuan',22,100) >>> import json >>> print(json.dumps(s)) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "G:\Anaconda\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "G:\Anaconda\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "G:\Anaconda\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "G:\Anaconda\lib\json\encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'Student' is not JSON serializable
修改之后变为:
>>> >>> class Student(object): ... def __init__(self,name,age,score): ... self.name=name ... self.age=age ... self.score=score ... >>> def student2dict(std): ... return {'name':std.name,'age':std.age,'score':std.score} ... >>> import json >>> s=Student('xuanxuan',22,100) >>> print(json.dumps(s,default=student2dict)) {"name": "xuanxuan", "age": 22, "score": 100} >>>
另外还可以:
>>> >>> class Student(object): ... def __init__(self,name,age,score): ... self.name=name ... self.age=age ... self.score=score ... >>> s1=Student('xuanxuanzhang',23,100) >>> import json >>> print(json.dumps(s1,default=lambda obj:obj.__dict__)) {"name": "xuanxuanzhang", "age": 23, "score": 100} >>>
>> class Student(object): ... def __init__(self,name,age,score): ... self.name=name ... self.age=age ... self.score=score ... >>> def dict2student(d): ... return Student(d['name'],d['age'],d['score']) ... >>> json_str = '{"age": 20, "score": 88, "name": "Bob"}' >>> print(json.loads(json_str,object_hook=dict2student)) <__main__.Student object at 0x0000015DAC52CD30> >>>
当遇到dict中出现中文需要序列化时:
>>> >>> import json >>> d=dict(name='璇璇',age=20) >>> s=json.dumps(d,ensure_ascii=True) >>> print(s) {"name": "\u7487\u7487", "age": 20} >>> s2=json.dumps(d,ensure_ascii=False) >>> print(s2) {"name": "璇璇", "age": 20} >>>
相关文章推荐
- 这篇文章记录廖雪峰python教程的习题(九)
- 这篇博客记录廖雪峰python教程的习题(五)
- 这篇博客记录廖雪峰python教程的习题(三)
- 这篇博客记录廖雪峰python教程的习题(七)
- 这篇博客记录廖雪峰python教程的习题(四)
- 这篇博客记录廖雪峰python教程的习题(六)
- 这篇博客记录廖雪峰python教程的习题(一)
- 这篇博客记录廖雪峰python教程的习题(二)
- 这篇文章记录廖雪峰pyton教程的习题(八)
- 廖雪峰的Git、Python教程
- 读廖雪峰的 Python 教程小结--------Python基础
- 廖雪峰Python教程1轮还没学明白的(3) -- 面向对象高级编程 -- 定制类 -- __getattr__之链式调用
- 廖雪峰的0Python教程
- 看python教程的一点小记录
- 廖雪峰python教程阅读之使用list和tuple
- 据廖雪峰python3教程----python学习第八天
- 【代码】廖雪峰Python教程,简单分布式进程
- 据廖雪峰python3教程----python学习第四天
- Python 爬虫:把廖雪峰的教程转换成 PDF 电子书
- Python+Django+SAE系列教程13-----MySQL记录的添\删\改