The path to learning in Python-day5

Source: Internet
Author: User
Tags function prototype shuffle timedelta

The content of this section:

Module explanation

1. Module definition

2. Os&sys Module

3. Time&datetime Module

4. Random Module

5. Shutil Module

6. Shelve Module

7. Configparser Module

8. Hashlib Module

9. Re Module

first, the module definition

1. Import the module

Import

Import main #导入这个模块 (file), is to explain the Python file again
Print (main.name)

Main.logger #调用main文件里面的logger函数

From main import Logger
Logger () #使用from在main. py file to import the logger function, the following can be used directly inside the main file logger function

Main.py:

# __author__ = ' LW '
name = ' LW '
def logger ():
Print (' This is a test ')

The essence of the import package is to execute the __init_.py file under the package (print test in the __init__.py File)

second, Os&sys Module

Import Os,sys

Absolute path to the print (os.path.abspath (__file__)) file

Print (os.path.dirname (os.path.abspath (__file__)))) #文件路径的文件夹的路径

Print (os.path.dirname (os.path.dirname (os.path.abspath (__file__)))) #文件路径的文件夹的路径的父目录的路径

Sys.path.append (x) Add this path to the environment variable to import the module in this directory

OS Module

Provides an interface to invoke the operating system

os.getcwd () Gets the current working directory, which is the directory path of the current Python script work os.chdir ("dirname") To change the current script working directory, equivalent to the shell under Cdos.curdir return to the current directory: ('.') Os.pardir Gets the parent directory string name of the current directory: ('..') Os.makedirs ('dirname1/dirname2') to generate a multi-level recursive directory Os.removedirs ('dirname1'If the directory is empty, it is deleted and recursively to the previous level of the directory, if it is also empty, then delete, and so on Os.mkdir ('dirname') to generate a single-level directory, equivalent to the shell mkdir Dirnameos.rmdir ('dirname'Delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir Dirnameos.listdir ('dirname'lists all files and subdirectories under the specified directory, including hidden files, and prints a list of Os.remove () deletes a file Os.rename ("oldname","newname") Rename file/Catalog Os.stat ('Path/filename') Get file/directory information os.sep output operating system-specific path delimiter, win under"\\", under Linux for"/"os.linesep Output The line terminator used by the current platform, win under"\t\n", under Linux for"\ n"the OS.PATHSEP output string that is used to split the file path (the current system Delimiter) os.name the output string to indicate the current use of the Platform. Win-'NT'; Linux->'POSIX'Os.system ("Bash Command"run the shell command to directly display the Os.environ get system environment variable Os.path.abspath (path) return path normalized absolute path Os.path.split (path) Split path into directory and file name two tuples return os.path.dirname (path) to the directory where path is Returned. In fact, the first element of Os.path.split (path) Os.path.basename returns the last file name of Path. If path ends with a/or \, then a null value is Returned. The second element of Os.path.split (path), os.path.exists (path), returns True if Path exists, or if path does not exist, returns Falseos.path.isabs if path is an absolute path, Returns Trueos.path.isfile (path) If path is an existing file and returns True. otherwise, return Falseos.path.isdir (path) True if path is a directory that Exists.  Otherwise return Falseos.path.join (path1[, path2[, ...])  When multiple paths are combined, the parameters before the first absolute path are ignored Os.path.getatime (path) returns the last access time of the file or directory to which path is pointing os.path.getmtime (path) Returns the last modified time of the file or directory to which path is pointing
three, time&datatime Module

Time.time () #time. Time () timestamp, number of seconds in 1970 to present

Tiem.sleep (2) #休息几秒

Time.gmtime () #时间戳换成UTC时区的时间的元组, No parameter default time stamp

Time.localtime () #元组的形式获取当前时间

Import=time.localtime ()print(x.tm_year)       # what year is it now Import=time.localtime (152533333)print(x.tm_year)

strftime ("format", tuple form of Time) #将当前时间 (tuple Form) converted to formatted string time

Import== time.strftime ("%y-%m-%d%h:%m:%s", X)   # format customization,%y is actually x.tm_year, one analogy Print (y)

Strptime ("formatted string", "format") #将当前时间的格式化字符串格式转成元组形式

z = time.strptime ("2016-08-20 14:42:52","%y-%m-%d%h:%m:%s " )print(z)

Asctime () #将元组形式的时间转换成字符串, No arguments, default is LocalTime ()

t = time.asctime ()print(t)

#时间加减

Importdatetime#print (datetime.datetime.now ()) #返回 2016-08-19 12:47:03.941925#print (datetime.date.fromtimestamp (time.time ())) # Timestamp goes directly to the date format 2016-08-19#Print (datetime.datetime.now ()#print (datetime.datetime.now () + datetime.timedelta (3)) #当前时间 + 3 days#print (datetime.datetime.now () + datetime.timedelta ( -3)) #当前时间-3 days#print (datetime.datetime.now () + datetime.timedelta (hours=3)) #当前时间 + 3 hours#print (datetime.datetime.now () + datetime.timedelta (minutes=30)) #当前时间 +30 points#c_time = Datetime.datetime.now ()#print (c_time.replace (minute=3,hour=2)) #时间替换
Iv. Random Module
1 ImportRandom2 Print(random.random ())#Random number,3 Print(random.randint (1,3))   4==================================5  ImportRandom6 Print(random.random ())#0.64450108633112937 #random.random () is used to generate a random number of 0 to 1 Points: 0 <= N < 1.08 Print(random.randint (1,7))#49 #the function prototype for Random.randint () is: random.randint (a, b), which is used to generate integers in a specified range. Ten  one #where parameter A is the lower limit, parameter B is the upper limit, the generated random number n:a <= n <= b a Print(random.randrange (1,10))#5 - #the function prototypes for Random.randrange are: random.randrange ([start], stop[, step]), - #gets a random number in the collection that increments by the specified cardinality, from within the specified range. Such as: random.randrange (ten, 2), the #the results are equivalent from [10, 12, 14, 16, ... 96, 98] gets a random number in the Sequence.  - #random.randrange (10, 100, 2) is equivalent to Random.choice (range (10, 100, 2) on the Result.  - Print(random.choice ('Liukuni'))#I - #Random.choice gets a random element from the Sequence.  + #its function prototype is: Random.choice (sequence). The parameter sequence represents an ordered Type.  - #Here's A note: sequence is not a specific type in python, but a series of types.  + #list, tuple, string all belong to Sequence. For sequence, You can view the Python manual data Model Chapter.  a #Here are some examples of using choice: at Print(random.choice ("Learn python"))#Learn - Print(random.choice (["Jgood"," is","a","Handsome"," boy"]))#List - Print(random.choice ("Tuple","List","Dict")))#List - Print(random.sample ([1,2,3,4,5],3))#[1, 2, 5] - #the function prototype for random.sample is: random.sample (sequence, k), which randomly fetches fragments of the specified length from the specified sequence. The sample function does not modify - example: in ImportRandom - Importstring to #Random integers: + Print(random.randint (0,99))# - - #randomly select even numbers between 0 and 100: the Print(random.randrange (0, 101, 2))#4 * #Random floating point number: $ Print(random.random ())#0.2746445568079129Panax Notoginseng Print(random.uniform (1, 10))#9.887001463194844 - #Random characters: the Print(random.choice ('abcdefg&#%^*f'))#F +  a #Select a specific number of characters in more than one character: the Print(random.sample ('Abcdefghij', 3))#[' F ', ' h ', ' d '] +  - #randomly pick a string: $ Print(random.choice (['Apple','Pear','Peach','Orange','Lemon'] ))#Apple $  - #Shuffle # -Items = [1,2,3,4,5,6,7] the Print(items)#[1, 2, 3, 4, 5, 6, 7] - random.shuffle (items)Wuyi Print(items)#[1, 4, 7, 2, 5, 3, 6]

The path to learning in Python-day5

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.