File read/write
Read File : Open (), read (), close (). Operations for files are generally put in try ... except ... finally
A complete file read code:
try:f = open ('/path/to/file ', ' R ') print (F.read ()) Finally:if F:f.close ()
Shorthand:
With open ('/path/to/file ', ' R ') as F:print (F.read ())
The advantage of shorthand is that it is concise and does not have to call the close () method.
Read () reads everything at once to prevent the file from being too large for memory overflow, and you can repeatedly call the read (size) method to read up to size bytes of content at a time. ReadLine () reads one line at a time, readlines () fetches all the contents one at a time and returns the list by row.
Open () Returns an object that has a read () called file-like. It can also be a byte stream, a network stream, a custom stream. It does not require inheritance from a particular class, as long as the read () method is written.
Opening a binary requires a B- mode .
f = open ('/path/to/file ', ' RB ') F.read ()
To read non-UTF8 text, you need to pass the encoding parameter to the open ().
f = open ('/path/to/file ', ' R ', encoding= ' GBK ' F.read ()
Encoding of non-canonical files, the open () function can use the errors parameter, the processing of encountering coding errors is generally ignored
f = open ('/path/to/file ', ' R ', encoding= ' GBK ', Errors=ignore ')
Write file : Open (), write (), close (). and read the same file. When calling open (), use ' W ' or ' WB '.
f = open ('/path/to/file ', ' W ') f.write ("Hello, World") F.close ()
Data loss by way of writing files, using the WITH statement:
With open ('/path/to/file ', ' W ') as F:f.write (' Hello, World ')
Write a specially encoded file, using the open () function to pass in the encoding parameter.
Use Stringio and Bytesio when writing memory streams
Str writes Stringio, it needs to create a stringio, and then writes.
From io Import stringiof = Stringio () f.write (' Hello world! ') Print (F.getvalue ()) Hello world!
GetValue () gets the written str.
Read the contents of the Stringio
From io Import stringiof = Stringio (' hello\nhi\ngoodbye!) While true:s = F.readline () if s = = ": Break print (S.strip ()) hellohigoodbye!
Binary operation using Bytesio
From io Import bytesiof = Bytesio () f.write (' Chinese '. Encode (' Utf-8 ')) print (F.getvalue ()) B ' \xe4\xb8\xad\xe6\x96\x87 '
Read operation with Stringio ()
Operation of files and directories
Use the OS and Os.path modules.
Os.name
Os.uname ()
Os.environ
Os.environ.get (' PATH ')
Os.path.abspath ('. ')
Add a directory to another directory
Os.path.join ('/path/to ', ' Test ') add test to the to
Os.mkdir ('/path/to/test ') create a directory
Os.rmdir ('/path/to/test ') Delete a directory
Os.path.split ('/path/to/test/test.txt ') splits the path of a file to an absolute path and a filename.
('/path/to/test ', ' test.txt ')
Os.path.splitext ('/path/to/test.txt ')
('/path/to/test ', '. txt ')
The above operations do not require a directory or file to exist, just the manipulation of the string.
Os.rename (' test.txt ', ' test.py ') file renamed
Os.remove (' test.py ') Delete file
Shutil Module provides the function of file copy CopyFile ()
Serialization of --Pickling deserialization- -unpickling
Other languages are called serialization,marshalling,flattening
Serialization: The process of changing a variable from memory to a storage or transfer. After serialization, the serialized content can be written to disk or transmitted.
Deserialization: Re-reads the contents of the variable from the serialized object into memory.
To serialize and deserialize an instance:
Import pickled = Dict (name= ' Bart ', Age=20, score=88) pickle.dumps (d) f = open (' Dump.txt ', ' WB ') Pickle.dump (d, f) f.close () f = open (' Dump.txt ', ' RB ') d = pickle.load (f) f.close () d{' age ': +, ' score ': ", ' name ': ' Bart '}
JSON operation--Python is faster than XML in JSON.
Import Jsond = Dict (name= ' Bart ', Age=20, score=88) json.dumps (d) json_str = ' {' Age ': $, ' score ': "The name": "Bart"} ' Json.loads (JSON_STR) {"Age": $, "score": "The", "name": "Bart"}
Serializes an object into a JSON
Import jsonclass student (object): def __init__ (self, name, age , score): self.name = name self.age = age Self.score = score s = student (' Bart ', 20, 88) # print (Json.dumps (s)) typeerror# use the optional parameters of dumps Defalut to turn any object into a JSON-serializable object. A function is required to convert. DEF&NBSP;STUDENT2DICT (STD): return { ' name ': std.name, ' age ': std.age, ' score ': std.score } Print (Json.dumps (s, default=student2dict)) {"Age":20, "name":bart, "Score":88}# Change any class to Dict:print (Json.dumps (S,&Nbsp;default=lamba obj:obj.__dict__)) # class instances have a __dict__ attribute. In addition to __slots__ 's class# to deserialize JSON into a student object instance, loads () first converts a Dict object, and the incoming Object_hook function is responsible for converting dict to student instance: def dict2student (d): return student (d[' name '], d[' age '], d[' score ']) json_str = ' {"Age":20, "name": "Bart", "score": "The" "Print" ( Json.loads (json_str, object_hook=dict2student)) <__main__. Student object at 0x10cd3c190>
Python I/O programming