Python path "fifth": Python Basics (20)-modules, serialization, OS modules

Source: Internet
Author: User
Tags create directory file separator local time posix string format timedelta

Common Module Time Module time.time ()
Import  Time Import datetime Print # returns the timestamp of the current time
Time.ctime ()
Print # Convert timestamp to string format wed Feb 17 11:41:27 2016, the default is the timestamp of the current system time Print # CTime can receive a timestamp as a parameter, returning the string form of the timestamp Wed 10:43:04
Time.gtime ()
Print # Convert timestamp to struct_time format, default is current system timestamp Print (Time.gmtime (Time.time ()-3600))
Time.localtime ()
Print # The same time stamp is converted to struct_time, except that the local time is displayed, Gmtime shows the standard Time (Galini time)
Time.mktime ()
Print # Convert struct_time time format to timestamp
Time.strftime ()
Print (Time.strftime ("%y-%m-%d%h:%m:%s"# converts the struct_time time format into a custom string format
Time.trptime ()
Print (Time.strptime ("2016-02-17""%y-%m-%d"# convert string format to Struct_time format, as opposed to Trftime
Time.asctime ()
Print # Convert struct_time to string form
DateTime module
    • Datetime.date: A class that represents a date. Common attributes are year, month, day
    • Datetime.time: A class that represents time. Common properties are hour, minute, second, microsecond
    • Datetime.datetime: Represents the date time
    • Datetime.timedelta: Represents a time interval, that is, the length between two points in time
Datetime.date.today ()
Print # returns the string form of the current date 2016-02-17
Datetime.date.fromtimestamp ()
Print # Converts a timestamp into a date string form 2016-02-16
Datetime.datetime.now ()
Print # returns the time of the string form 2016-02-17 13:53:30.719803 Print # Convert to Struct_time format
Datetime.timedelta ()

Datetime.timedelta () Returns a time interval object, often combined with datetime.datetime.now () to compute time

Print (Datetime.datetime.now ()-Datetime.timedelta (days = 2))
Random module

The random module is primarily used to generate

Random ()

Generate a random number of floating-point types greater than 0 and less than 1

Print # generate a random number of floating-point types greater than 0 and less than 1
Serialization of

Two modules for serialization in Python

    • JSON is used to convert between "string" and "Python Basic data Types"
    • Pickle for "Python-specific type" and "Python basic data type" to convert between

The JSON module provides four functions: dumps, dump, loads, load

The Pickle module provides four functions: dumps, dump, loads, load

OS Module

Provides an interface to invoke the operating system

>>>ImportOS>>> OS.GETCWD ()#get current working directory, Linux-like pwd command'/data/python/day5'>>> Os.chdir ('..')#Enter a directory, Linux-like CD command>>>OS.GETCWD ()'/data/python'>>> Os.curdir#Get current directory'.'>>> Os.pardir#gets the parent directory of the current directory'..'>>> Os.chdir ('Day5')>>>OS.GETCWD ()'/data/python/day5'>>> Os.makedirs ('Testdir1/testdir2')#recursive creation of directories equivalent to the MKDIR-P command>>> Os.makedirs ('Test_dir1/test_dir2')#recursive creation of directories equivalent to the MKDIR-P command>>> Os.listdir ('.')#displays all the files in the directory equivalent to the Linux ls-a['Test_dir1']>>> Os.removedirs ('Test_dir1/test_dir2')#Delete the multi-level (recursive) directory, note that the directory must be empty, if the directory is empty delete, and recursively to the upper and the directory, if also empty also deleted>>> Os.mkdir ('test2')#Create directory, equivalent to mkdir>>> Os.rmdir ('test2')#Delete directory, equivalent to RM>>> f = open ('Test.txt','W')>>> F.write ('Testline')8>>>f.close ()>>>Os.listdir () ['Testdir2','Test.txt','Testdir1']>>> Os.rename ('Test.txt','New_test.txt')# Renaming>>> Os.stat ('.')#Displays the status of a directory or file, including permissions, etc.Os.stat_result (st_mode=16877, st_ino=786731, st_dev=64784, st_nlink=4, St_uid=0, St_gid=0, st_size=4096, st_atime= 1455695375, st_mtime=1455696066, st_ctime=1455696066)>>> Os.sep#gets the file separator, Linux for/,windows \ \'/'>>> Os.name#returns the platform name, Linux for Posix,win NT'POSIX'>>> Os.linesep#returns system line break, win under \ r \ n'\ n'>>> Os.pathsep#returns the string used to split the file path, under Vin;':'>>> Os.system ('ls')#Execute shell CommandTestdir1 Testdir20>>> Os.environ#Get system Environment variablesEnviron ({'USER':'Root','PATH':'/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin','SHELL':'/bin/bash','HOME':'/root','SHLVL':'1','Histtimeformat':'%... Omit n much better ...>>> Os.path.abspath ('.')#returns the absolute path of the directory'/data/python/day5'>>> Os.path.split ('/data/python/day5')#the path is partitioned into directories and files, and Ganso returns('/data/python','Day5') >>> Os.path.dirname ('/data/python/day5')#return path is also the first element of split'/data/python'>>> Os.path.basename ('/data/python/day5')#The return file name is also the first element of split'Day5'>>> os.path.exists ('/data/python/day5')#determine if a directory or file existsTrue>>> Os.path.isabs ('/data/python/day5')#determine if it is an absolute directory, regardless of whether it exists, and plainly that the string conforms to the absolute path of the specification returns trueTrue>>> Os.path.isabs ('Day5') False>>> Os.path.isabs ('/data/python/day6')# True>>> Os.path.isfile ('/data/python/day5')#determine if it is a fileFalse>>> Os.path.isdir ('/data/python/day5')#determine if it is a directoryTrue>>> Os.path.isdir ('/data/python/day6') False>>> Os.path.join ('/data/python/day6','Test')#Combined Catalog'/data/python/day6/test'>>> Os.path.getatime ('/data/python/day5')#returns the last access time for a file or directory1455695375.9394312>>> Os.path.getmtime ('/data/python/day5')#returns the last modified time of a file or directory1455696066.0034554>>> Os.path.getctime ('/data/python/day5')#returns the creation time of a file or directory1455696066.0034554

Python path "fifth": Python Basics (20)-modules, serialization, OS modules

Related Article

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.