9 IO Programming
In Python, file reads and writes are done through file objects opened by the open () function. Using the WITH statement to manipulate file IO is a good habit.
Read the file
Try
f = open ('/path/to/file ', ' R ')
Print (F.read ())
Finally
If f:
F.close ()
Python introduces a with statement to automatically call the close () method for us:
With open ('/path/to/file ', ' R ') as F:
Print (F.read ())
To read a binary file, compare slices, videos, etc., open the file with ' RB ' mode
>>> f = open ('/users/michael/test.jpg ', ' RB ')
>>> F.read ()
B ' \xff\xd8\xff\xe1\x00\x18exif\x00\x00 ... ' # Hexadecimal representation of bytes
Coding is not standardized, ignoring the wrong wording
f = open ('/users/michael/gbk.txt ', ' R ', encoding= ' GBK ', errors= ' ignore ')
F.readline (), f.read (size) fixed read file size
Write a file
----------
9.2 Character Byte Stringio Bytesio
Stringio and Bytesio are methods of operating str and bytes in memory, allowing for a consistent interface to read and write files.
From IO import Stringio
>>> f = Stringio (' hello!\nhi!\ngoodbye! ')
>>> while True:
... s = f.readline ()
... if s = = ":
... break
... print (S.strip ())
----------Stringio, as the name implies, reads and writes STR in memory.
>>> from IO import Bytesio
>>> f = Bytesio ()
>>> f.write (' Chinese ' encode (' utf-8 '))
6
>>> print (F.getvalue ())
B ' \xe4\xb8\xad\xe6\x96\x87 '
# # #BytesIO实现了在内存中读写bytes,
-------------
9.3 Manipulating files and directories
Os.environ.get (' PATH ')
The Os.path.split () function allows you to split a path into two parts, followed by a directory or file name that is always the last level:
>>> os.path.split ('/users/michael/testdir/file.txt ')
('/users/michael/testdir ', ' file.txt ')
To list all. py files
>>> [x for X in Os.listdir ('. ') if Os.path.isfile (x) and Os.path.splitext (x) [1]== '. Py ']
-----------
9.4 Python provides the Pickle module for serialization. The process of changing a variable from memory to a storage or transfer is called serialization.
>>> Import Pickle
>>> d = dict (name= ' Bob ', age=20, score=88)
>>> Pickle.dumps (d)
B ' \x80\x03}q\x00 (x\x03\x00\x00\x00ageq\x01k\x14x\x05\x00\x00\x00scoreq\x02kxx\x04\x00\x00\x00nameq\x03x\x03\ X00\x00\x00bobq\x04u. '
Pickle.dump () Serializes the object directly after it writes a File-like object:
>>> f = open (' Dump.txt ', ' WB ')
>>> Pickle.dump (d, F)
>>> F.close ()
When we want to read the object from disk to memory, we can read the contents to a bytes and then deserialize the object with the Pickle.loads () method.
>>> f = open (' Dump.txt ', ' RB ')
>>> d = pickle.load (f)
>>> F.close ()
>>> D
{' Age ': ' Score ': ' The ' name ': ' Bob '}
Json
Python IO Programming