Python IO operations

Source: Internet
Author: User

File read/write

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.

Try: F= Open ('1.txt','R')#RB Write Binary    #f = open (' 1.txt ', ' W ') #wb读二进制F.read (). Decode ('UTF8')    #f.write (' Test '). Encode (' UTF8 ')finally:    ifF:f.close () with write: with open ('1.txt','R') as F:PrintF.read ()

If the file is very small, read () One-time reading is the most convenient, if the file size can not be determined, repeated calls to read (size) comparison insurance, if it is a configuration file, call ReadLines () the most convenient

Directory Operations

When synthesizing two paths, do not spell the string directly, but pass the Os.path.join () function so that the path separators of different operating systems can be handled correctly.
Similarly, to split a path, do not go directly to the string, but through the os.path.split () function, so that a path can be split into two parts, the latter part is always the last level of the directory or file name

gets the current working directory, which is the directory path of the current Python script: OS.GETCWD () returns all files and directory names under the specified directory: Os.listdir () verifies whether the given path is a file: Os.path.isfile () Verify that the given path is a directory: Os.path.isdir () determines if the path is absolute: Os.path.isabs () verifies that the given route is really saved: os.path.exists () returns the directory name and file name of a path: o S.path.split () Detach extension: Os.path.splitext () gets the path name: Os.path.dirname () gets the file name: Os.path.basename () Get file properties: Os.stat (file) gives the line terminator used by the current platform: Os.linesep Windows uses'\ r \ n', Linux uses'\ n'and Mac uses'\ r' Create an empty file Os.mknod ("Test.txt") to create a directory Os.mkdir ("file") Copy file shutil.copyfile ("Oldfile","NewFile")#Oldfile and NewFile can only be files .Shutil.copy ("Oldfile","NewFile")#Oldfile can only be a folder, NewFile may be a file, or it can be a destination directory Copy Folder Shutil.copytree ("Olddir","Newdir")#Olddir and Newdir can only be directories, and newdir must not exist Move files / Catalog shutil.move ("Oldpos","Newpos") Rename file / Catalog os.rename ("oldname","newname") Delete file os.remove ("file") Delete directory Os.rmdir ("dir")#only empty directories can be deletedShutil.rmtree ("dir")#empty directories, contents of the directory can be deleted Convert directory os.chdir ("c:\\123")#set the current directory to "C:\123", which is equivalent to the doc command's CD C:\123

File-like Object

Like the open () function, this object, which has a read () method, is called File-like object in Python. In addition to file, it can be memory byte stream, network stream, custom stream and so on. File-like object does not require inheritance from a particular class, just write a read () method on the line.

Stringio is a file-like Object that is created in memory and is commonly used as a temporary buffer.

Serialization of

The process of changing a variable from memory to a storage or transfer is called serialization, and in Python it is called pickling, which is also called serialization,marshalling,flattening in other languages, and so on.
In turn, re-reading the variable contents from the serialized object into memory is called deserialization, i.e. unpickling.

If we are going to pass objects between different programming languages, we must serialize the objects into standard formats, such as JSON

The data types built into JSON and Python correspond to the following:

JSON type Python type
{} Dict
[] List
"String" ' Str ' or U ' Unicode '
1234.56 int or float
True/false True/false
Null None

For simple data types (string, Unicode, int, float, list, tuple, dict), they can be processed directly.

Serialization of
The dumps () method returns a str with the content being the standard JSON.
The dump () method can write JSON directly to a file-like Object.

Deserialization
Loads () deserializes a JSON string
Load () reads the string from the File-like object and deserializes it

>>>ImportJSON>>> d = dict (name='David', Age=20, score=100)>>> D_encode =Json.dumps (d)>>>D_encode'{"Age": +, "score": +, "name": "David"}'>>> with open ('D:\\1.txt','WB') as F:d_encode_file=Json.dump (d, F)>>> D_decode =json.loads (D_encode)>>>D_decode{u' Age': +, U'score': +, U'name': U'David'}>>> with open ('D:\\1.txt','RB') as F:d_decode_file=json.load (f)>>>D_decode_file{u' Age': +, U'score': +, U'name': U'David'}

Encode,decode an instance object of class to JSON

ImportJSONclassStudent (object):def __init__(self, name, age, score): Self.name=name Self.age=Age Self.score=scoredefstudent2dict (STD):return {        'name': Std.name,' Age': Std.age,'score': Std.score}defDict2student (d):returnStudent (d['name'], d[' Age'], d['score']) s= Student ('David', 20, 100)Print(Json.dumps (S, default=student2dict))#Optional parameter default is to turn any object into an object that can be serialized as JSONJson_str='{"Age": +, "score": "," "Name": "Bob"}'Print(Json.loads (JSON_STR, object_hook=dict2student))#The loads () method first converts a Dict object, and the incoming Object_hook function is responsible for converting dict to student instances

2015-05-10

Python IO operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.