This article records the exercises of Liao Xuefeng's python course (9)

IO programming

File read and write

I don't need to go into details after contacting here, just go to the code:

# -*- 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()
'''


#To open a file, you need to close it. One way is to use try...finally... And the other way is to use 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()
'''

#Using with and try...finally works the same, but the code is simpler and the close() function is not written
'''
def main():
    with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') as file:
        print(file.read())
main()
'''

#Now familiarize yourself with the readlines() function
'''
def main():
    with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan.txt",'r') as file:
        for line in file.readlines(): #The readlines() function will read all the contents of the file and save them into a list. Each line is an element of the list
            #print(line.strip())  #strip() function takes out the tail \ n
            print(line)

main()
'''

#Now familiarize yourself with the readline() function
'''
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()
'''

#The above are all open text files. If you are opening binary files, you only need to'rb'that will do
'''
def main():
    file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/cat.jpg",'rb')
    print(file.read())
    file.close()
main()
'''

#In addition, if you want to write files of other encoding formats, you can use the encoding parameter of the open() function to set the corresponding 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()
'''

#If other types of encoding formats are mixed in the text, Unicode encodeerror will appear. You only need to pass in the value ignore through the error parameter of the open() function, that is, directly ignore the relevant errors
'''
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()
'''

#When we need to write files like disks, we must wait until the open files are closed before we can see the changes in the contents of the files
'''
def main():
    file=open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan2.txt",'w')
    file.write("Hahaha, I just try to write data to the disk!")
    file.close()  #When using the write operation, be sure to close the file after writing, otherwise you will not see the data

main()
'''
#Using with code is simpler and no need to write 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()
'''

#In fact, you will find that when you write data to disk in w mode, the next operation will overwrite the previous one, so we need to use the additional method: a

def main():
    with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan2.txt",'a') as file:
        file.write("Attention, I'm the addition!")

main()

Here is an exercise:
Please read a local text file as a str and print it out:

def main():

    with open("E:/pyhtonworkspace/py3-pratice/bymyself_practice/python_Liaoxuefeng/20180227/xuanxuan3.txt") as file:
        s=file.read()
        print(s)
main()

StringIO and BytesIO

First, there are two modes to use StringIO: the first is that StringIO() directly write s in with no parameters and then reads str with getvalue(); the other is to use StringIO() to read str content and then use readline() to read function content

>>> from io import StringIO
>>> file=StringIO()
>>> file.write("Study hard")
4
>>> file.write("Make progress every day")
4
>>> file.getvalue()
'study hard and make progress every day'
>>>
>>> from io import StringIO
 >>>File = stringio ("study hard \ n day up \ n come on! ""
>>> while True:
...     content=file.readline()
...     if content=='':
...         break
 ... print(content) ා if you don't want the space between the output results to be too large, you can use the content.strip() function to remove the tail \ n
...
Study hard

Make progress every day

Come on!
>>>
>>> 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() #First create a BytesIO() and then write
>>> file.write("Ha-ha".encode('utf-8'))
6
>>> file.getvalue()  #getvalue() method gets the value
b'\xe5\x93\x88\xe5\x93\x88'
 from io import BytesIO
>>> file=BytesIO(b'\xe7\x92\x87\xe7\x92\x87')   #You can also use one first bytes Initialization BytesIO And then read it like a file
>>> file.read()
b'\xe7\x92\x87\xe7\x92\x87'
>>>
>>> from io import StringIO
 >>>File = stringio ("Xuan \ n is a good child! \n ""
>>> for line in file.readlines():
...     print(line.strip())
...
Xuan Xuan
 It is a
 Good boy!
>>>
>>> from io import StringIO
 >>>File = stringio ("Xuan \ n is a good child! ""
>>> file.read()
'Xuan Xuan is a good child! '
>>>
>>> from io import StringIO
 >>>File = stringio ("Xuan \ n is a good child! ""
>>> while True:
...     content=file.readline()
...     if content=='':
...         break
...     print(content.strip())
...
Xuan Xuan
 It is a
 Good boy!

serialize

I found I couldn't understand. Oh, Doc
Direct previous code:

>>>
>>> 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 objects can be converted to strings using 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}
#If it is not a dict object, it is a class object
>>>
>>> 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

Changed to:

>>>
>>> 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}
>>>

In addition, you can:

>>>
>>> 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>
>>>

When Chinese in dict needs to be serialized:

>>>
>>> import json
>>> d=dict(name='Xuan Xuan',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": "Xuan Xuan", "age": 20}
>>>

Tags: JSON encoding Anaconda Programming

Posted on Thu, 02 Apr 2020 00:04:52 -0700 by alchemist_fr