Python Common Modules

Source: Internet
Author: User

One, the JSON module

JSON (JavaScript Object Notation) JavaScript objects tags, JS object notation, JS data format.

Currently (today March 31, 2018), most of the data passed from the front end is in JSON format, and the backend needs to be converted. Is that JS interacts with Python.

(i). Precautions

(1). The JSON object must be a string

(2). In a JSON object, you must use double quotation marks whenever you want to represent a string.

(3). In a JSON object, single quotes cannot appear. Same 2

(b). A few common methods

(1). Json.dumps (Dict_object) Converts a Python Dictionary object to a JSON object

(2). Json.loads (Json_object) converts a JSON object into a python dictionary

(3). Json.dump (Dict_object, open ("File_name.json", "W")) converts a dictionary to a JSON object and saves it as a JSON file

(4). Json.load ("File_name.json") directly converts the JSON object in the file into a dictionary

Second, OS module

Directory and file operations, the same effect as the Linux command.

Like what:

Os.listdir (path), LS

Os.makedirs ("name"), mkdir

(a). Practice:

Write a function that traverses the path, all directories and subdirectories

"""write a function that traverses the path, all directories and subdirectories"""ImportOSdefList_all_file (File_path): Paths=Os.listdir (File_path) foreachinchPaths:path_next=Os.path.join (File_path, each)ifOs.path.isdir (Path_next): List_all_file (Path_next)Else:            Print(Os.path.join (File_path, Path_next)) List_all_file (R"D:\python_local")
View Code

Third, datetime module

Specific use, the specific Google it

Note the point:

(i). Strptime () before and after the same format. In parentheses, the preceding time string is "-", and then the string to be formatted must be "-".

(b). case, output a DateTime format with a time zone:

Import datetime def Utc_now ():     = Datetime.datetime.now ()    = datetime.datetime (dt.year, Dt.month, Dt.day,                                 dt.hour, Dt.minute, Dt.second, Dt.microsecond,                                 tzinfo=datetime.timezone.utc)    return  utc_ Timeprint(Utc_now ())#  2018-07-06 16:59:50.256989+00:00
View Code

Iv. Base64

is a character encoding, not an encryption.

The pictures and videos on the Web page are binary files.

Now the picture is generally not turned into a base64, a large string of code, the front-end still do not take a knife to kill you —.—

Five, log module

is to write a diary and record information.

Supplementary exercises:

"""The model of the producer consumer of OOP uses a module: thread requirements: Eat steamed buns, people who eat steamed buns, I want to make steamed buns and steamed buns at the same time, so that they achieve a relatively balanced"""Import TimeImportThreadingclassPersoneatbaozi (Threading. Thread):"""the people who eat steamed buns inherit threading directly. Thread"""    defRun (self): while1:            GlobalCountifCon.acquire ():#locked                ifCount < 100: con.wait ()#let the thread wait                Else: Count-= 30Print("{} Lao Wang ate 30 buns, and there were {} buns left.". Format (self.name, str (count))) con.notify ()#notify other threads, go to grab threadsCon.release ()#UnlockTime.sleep (1)classPersonmakebaozi (Threading. Thread):"""the man who makes buns"""    defRun (self): while1:            GlobalCountifCon.acquire ():ifCount > 1000: con.wait ()Else: Count+ = 100Print("{} Island song made 100 buns, a total of {} Buns". Format (self.name, str (count))) Con.notify () con.release () Time.sleep (1)if __name__=='__main__': Count= 500Con= Threading. Condition ()#Open Thread     forIinchRange (2):        #set up 2 people to make bunsPM =Personmakebaozi () Pm.start ( )#Start Thread     forIinchRange (5):        #set up 5 foodiePE =Personeatbaozi () Pe.start ( )
View Code

Python Common Modules

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.