Python Learning-Common module-os,random,logging

Source: Internet
Author: User

OS Module (Supplemental) 1. View current path and switch path

>>> Import OS
>>> OS.GETCWD () #获取当前文件所在的路径
' D:\\python\\lib\\idlelib '
>>> Os.chdir ('.. /') #切换当上一层目录, this can be a relative path
>>> OS.GETCWD ()
' D:\\python\\lib '

>>> os.chdir (' D:\Program Files (x86) ') #也可以是绝对路径
>>> OS.GETCWD ()
' D:\\Program Files (x86) '

Add:

Found on Pycharm that OS.GETCWD () and Os.path.realpath ("./") return the absolute path to the. py file, which is not the directory in which the script is located, but rather the directory in which the script is run.

Actually Os.path.relpath (path[, start]) #从start开始计算相对路径.

Print (__file__) • #返回文件的相对路径, including file name

Os.path.abspath (__file__) #返回文件的绝对路径, including file name

Os.path.dirname (Os.path.abspath (__file__)) #上一个路径的文件名称所在的目录, which is the previous level of the current file

Dis_path = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) #再往上一层, this can be used, through the import sys; Sys.path.append (Dis_path), add it to the environment variable so that you can implement a cross-path call file.

2. See if the file exists under the current path

os.path.exists (' filename '), Existence returns True

Can be used in conjunction with the above switch path to see if there is no such file under different paths

3, replacing and renaming files

Os.repalce ()

Replace (*args, **kwargs):

Rename a file or directory, overwriting the destination.
The previous file is replaced with a later filename

Os.rename ()

Use the same, but there is a difference

Os.replace (F1,F2) #f2如果存在, F1 still renamed F2 and replaced F2

Os.rename (F1,F2) #f2如果存在, error

Random module
1 Import Random 2 Print (Random.random ())  # print a random float number 3 Print # prints a random int number from 1 to 5, including 1 and 5 4 Print (Random.randrange (1,5))  # prints a random int number from 1 to 5, including 1, excluding 5

Output:

0.370659405830737342

Example: Generating a verification code

1 ImportRandom2Checkcode ="'3  forIinchRange (4):4Current = Random.randrange (0,4)5     ifCurrent! =I:6         """chr () returns the English letter of an integer corresponding to the ASCII code, where 65-90 represents 26 uppercase letters and 97-122 returns 26 lowercase letters. Instead, Ord (' a ') returns the corresponding number of the letter A in ASCII"""7temp = Chr (Random.randint (65,90))8     Else:9temp = Random.randint (0,9)TenCheckcode + =Str (temp) One Print(Checkcode)
Logging Module (supplemental)

There are 6 levels of logs, from high to low as follows:

CRITICAL = 50

FATAL = CRITICAL

ERROR = 40

WARNING = 30

WARN = WARNING

INFO = 20

DEBUG = 10

NOTSET = 0

1, by default, Longging will only speak warning above the level of the log print to the screen, including warning.

Import logging

# Logging.basicconfig ()

Logging.debug (' This is Debug ')

Logging.info (' This is info ')

Logging.warning (' This is warning ')

Logging.error (' This is error ')

Logging.critical (' This is critical ')

Output:

WARNING:root:this is WARNING

ERROR:root:this is Error

CRITICAL:root:this is CRITICAL

2. Configure the output format and mode of the log by Logging.basicconfig function

Import logging

Logging.basicconfig (filename= ' Log.log ',

format= '% (asctime) s-% (name) s-% (LevelName) s-% (module) s:% (message) s ',

datefmt= '%y-%m-%d%h:%m:%s%p ',

LEVEL=10)

Logging.debug (' This is Debug ')

Logging.info (' This is info ')

Logging.warning (' This is warning ')

Logging.error (' This is error ')

Logging.critical (' This is critical ')

A log.log file is generated and the log is appended to the file: The default is append.

As follows:

2017-05-25 18:09:13 pm-root-debug-logging Mod:this is DEBUG

2017-05-25 18:09:13 pm-root-info-logging Mod:this is INFO

2017-05-25 18:09:13 pm-root-warning-logging Mod:this is WARNING

2017-05-25 18:09:13 pm-root-error-logging Mod:this is ERROR

2017-05-25 18:09:13 pm-root-critical-logging Mod:this is CRITICAL

?

Parameters of the Logging.basicconfig function:

FileName: Specify the log file name

FileMode: Same as file function, specify open mode of log file, ' W ' or ' a '

Format: Specifies the formats and contents of the output, format can output a lot of useful information, as in the example above:

% (Levelno) S: Print the value of the log level

% (levelname) S: Print log level name

% (pathname) s: Prints the path of the currently executing program, which is actually sys.argv[0]

% (filename) s: Prints the current name of the executing program

% (funcName) s: Print the current function of the log

% (Lineno) d: Print the current line number of the log

% (asctime) s: Time to print logs

% (thread) d: Print thread ID

% (threadname) s: Print thread name

% (process) d: Print process ID

% (message) s: Print log information

DATEFMT: Specify time format, same as Time.strftime ()

Level: Sets the log levels by default to logging. WARNING

Stream: Specifies the output stream that will log, can specify output to Sys.stderr,sys.stdout or file, default output to Sys.stderr, stream is ignored when stream and filename are specified simultaneously

The above Log module reference: http://www.cnblogs.com/dkblog/archive/2011/08/26/2155018.html

Python Learning-Common module-os,random,logging

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.