20th Day Module sys OS OS path settings random shuit

Source: Internet
Author: User
Tags shuffle

A. SYS module

1.SYS.ARGV command line argument list, the first element is the path of the program itself

2.sys.exit (n) exit program, Exit normally (0)

3.sys.version getting version information for the PYTHONN interpreter

4.sys.maxint the largest int value

5.sys.path returns the search path of the module, initializing the value using the PYTHONPATH environment variable

6.sys.platform returns the operating system platform name

Expand

There are a lot of times when script execution requires a progress bar

How to Achieve

Print ("[# # #])

Print (' [# # #] ')

Print ("[#####]")

Analysis:

The symbol at the time of the fixed change of the bracket position

Format replacement plus placeholder print ("[%-50s]"% "#")

It's not a newline. Always in line refresh progress

is actually the new content that covers the old content feels like an animation

The width of the brackets should be not fixed according to the CMD adjustment, so as a parameter passed in

So print ("[%-%ds]")

I can't tell you that you're preaching more.

Defined as method

Do not wrap the print and move the cursor to the line actually

Two. OS Module

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work

Os.chdir ("DirName")

Os.curdir returns the current directory: (', ')

Os.pardir Gets the parent directory string name of the current directory: (' ... ')

Os.makedirs (' dirname1/dirname2 ') can generate multi-level recursive directories

Os.removedirs (' dirname1 ') if the directory is empty, then delete, and recursively to the previous level of the directory, if also empty

Then delete, and so on.

Os,mkdir (' dirname ') generates a single-level directory, equivalent to mkdir dirname in the shell

Os.rmdir (' diname ') Delete single-level empty directory, if the directory is not empty can not be deleted, error;

When RmDir dirname in the shell

Os,listdir (' dirname ') lists all files and subdirectories in the specified directory, including hidden files,

and print as a list

Os.remove () Delete a file

Os.rename (' oldname ', ' newname ') renaming files/directories

Os.stat (' path/filename ') get File/directory information

OS.SEP output operating system-specific path delimiter, win under "\ \", under Linux for OS.LINESEP output current platform use line terminator, win under "\t\n", Linus "\ n" os.pathsep output the string used to split the file path Win under for;, Linux for: Os.name output string indicates the current use of platform win-> ' NT '; Linux-> ' POSIX ' os.system (' Bash command ') runs a shell command that directly displays Os.environ get environment variables

Three path module
Os.path.abspath (path) returns the absolute path normalized by path
Os.path.split (path) divides the path into a directory and a filename? Two tuples return
Os.path.dirname (path) returns the directory of path. Os.path.split is actually the first
? An element
Os.path.basename (Path) returns the last file name of path. How path ends with/or \,
Then a null value is returned. Two elements of Os.path.split (path)
Os.path.exists (path) If path exists, returns true if path does not exist, returns
False
Os.path.isabs (path) If path is an absolute path, returns True
Os.path.isfile (path) If path is an existing? file, returns True. otherwise returns false
Os.path.isdir (path) returns True if path is an existing? directory. otherwise return
False
Os.path.join (path1[, path2[, ...]) combines multiple paths to return, and the first absolute path
The previous parameters will be ignored slightly
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?
Os.path.getsize (path) returns the size of the path?

# Normcase? Used to normalize the route to convert uppercase to lowercase slash to current system delimiter
Print (Os.path.normcase ("\\a\\b\\ABCS"))
# Normpath? Used to normalize road paths not only will the invalid delimiter be replaced with a valid delimiter but also
Uppercase to lowercase and will be in line. Back on the first floor?
Print (Os.path.normpath ("/a/b/. /abcs "))

5.setting

Import os# Direct write Dead can not cross the platform as far as possible using the following two kinds of Db_path= R"d:\ Shanghai python full stack Phase 4 \day19\db\ Kogan Db.txt"Log_path= R"d:\ Shanghai python full stack phase 4 \day19\log\log.txt"# The second way to Stitch cross-platform # get the current path # first # Base_dir2=Os.path.dirname (Os.path.dirname (__file__)) # Log_path2= Os.path.join (Base_dir2,"Log","Log.txt"# Print (log_path2) # The third splicing way cross-platform print (Os.path.normpath (__file__)) print (Os.path.normpath (Os.path.join (__file__ ,"..","..","Log","Log.txt")))

6 Stochastic module random

Import random# random number module print (Random.random ()) #0-1does not include 1 random floating-point print (Random.randint (1,Ten)) #1-Teninteger print that includes 1 and 10 (Random.randrange (1,Ten)) #1-10 includes 1 not including 10 integer print (random.sample (["AAA",["a","b"],3,4,5],2) # Specify a range and specify the desired number of random LS= ["1","2","3","4"]random.shuffle (LS) # scrambled the original list of shuffle changes (LS) print (Random.choice ([1,2,3]) # randomly select a print (Random.choices ([1,2,3,4,5,6,7],k=2) # Random selected number # random captcha length customization includes 0-9A-Zzdef get_auth_code (length): Res=""     forIinchRange (length): a= Random.randint (0,9) b= Chr (Random.randint ( $, -)) C= Chr (Random.randint ( the,122)) S=Random.choice ([a,b,c]) Res+=Str (s)returnResprint (Get_auth_code (4))

7 Shutil Module
Very simple? File operation compression package processing module
Shutil.copyfileobj copy? file provides two file objects? length indicates buffer? Small
Shutil.copyfile (SRC, D ST) copy of the two? File path
Shutil.copymode () copy? File permissions provide two? file path
Shutil.copystat (src, DST) copy? File status information last access last modified permission provided Two
file path paths
Shutil.copy (src, DST) copy? Files and permissions provide two file path paths
Shutil.copy2 (src, DST) copy? File and status information for two file path
Shu  Til.ignore_patterns ("MP3", "*.py")
Shutil.copytree (src, DST, symlinks=false, Ignore=none) copy of the Shell directory
Symlinks default false will the soft connection copy the shell as a hard link or copy the shell for the soft connection
Shutil.rmtree Delete? directory can be set to ignore a little? File
Shutil.move (src, DST)
move to directory and file

8. Compression and decompression
Shutil can be packaged but can't unpack and package is also a tune? Completed with Tarfile and ZipFile
Decompression needs to be adjusted according to the format of the corresponding module
Packaged
Shutil.make_archive ("Test", "tar", "/users/jerry/pycharmprojects/package/packa
Ge1 ")
Import Tarfile,zipfile
Zip compression
z = zipfile. ZipFile ("Test.zip", "W")
Z.write ("sys.py")
Z.write ("start.py")
Z.close ()
Zip decompression
z = zipfile. ZipFile ("Test.zip", ' R ')
Z.extractall ("/users/jerry/pycharmprojects/package/aaa")
Z.close ()
Tar compression
t = Tarfile.open ("Test.tar", "W")
T.add ("start.py")
T.add ("sys.py")
T.close ()
Tar decompression
t = Tarfile.open ("Test.tar")
T.extractall ("aaa/")
T.close ()

Homework:
Tomorrow's Dictation
Add engineering root to environment variable requirements can be cross-platform

Import os# Direct write Dead can not cross the platform as far as possible using the following two kinds of Db_path= R"d:\ Shanghai python full stack Phase 4 \day19\db\ Kogan Db.txt"Log_path= R"d:\ Shanghai python full stack phase 4 \day19\log\log.txt"# The second way to Stitch cross-platform # get the current path # first # Base_dir2=Os.path.dirname (Os.path.dirname (__file__)) # Log_path2= Os.path.join (Base_dir2,"Log","Log.txt"# Print (log_path2) # The third splicing way cross-platform print (Os.path.normpath (__file__)) print (Os.path.normpath (Os.path.join (__file__ ,"..",".."


1. Random Verification code exercise in class

# Random Verification code length customization includes 0-9 A-Z a-zdef get_auth_code (length    ):""for in     Range (length):         = Random.randint (0,9)        = Chr (random.randint) )        = Chr (Random.randint (122))        = Random.choice ([a,b,c])         + = Str (s    )return Res


2. Practice today's Shutil OS sys

20th Day Module sys OS OS path settings random shuit

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.