Beginner Python's Day5

Source: Internet
Author: User

One, the Python learning module:

1. The nature of the module:

The essence of a module is to logically organize Python code (variables, functions, classes, logic: Implementing a function). The python file at the end of the PY

2. How to use the module:

Import + file name such as: Import test1 ( filename must not Add. py)

Import multiple files is import+ file name, file name such as import Test1,test2

From test1 Import * Imports everything from the Test1 module and executes it all over again (not recommended)

From test1 import m1,m2,m3 imports m1,m2,m3 from the Test1 module separately

From test import logger as Logger_alex the module name imported is the same as the current function name, you can rename the imported module name with AS

3. The nature of the import:

The essence of the import module is to interpret the Python file again;

The essence of the import package is to execute the __init__.py file under the package;

4. Module classification:

Custom Modules

Built-in standard module (standard library)
Open source Module

4-1 Custom Modules

4-1-a. Absolute path to the current file:

Import os# importing OS module
dir = Os.path.abspath (__file__)
Print (dir)

4-1-b. The absolute path of the parent directory of the current file:

Import os# importing OS module
dir = Os.path.dirname (Os.path.abspath (__file__))
Print (dir)

4-1-c. The parent directory absolute path to the parent directory of the current file:

Import OS #导入os模块
dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__)))
Print (dir)


4-1-d. If the module is not in the same directory as the program you are writing, you can add the path of the module to the program by Sys.path.append (path).

Import Os,sys

dir = Os.path.dirname (Os.path.dirname (Os.path.abspath (__file__))) #获取python目录的绝对路径
Sys.path.append (dir) #讲python目录的路径添加到程序中
#-----You want to find the path quickly, you can insert the directory path that you will add to the path in front of it
# Sys.path.insert (dir)
Import old from read_new #导入read_new. py file

A function in the #在当前路径下调用read_new. PY, such as user ()
Read_new.user ()

4-2 built-in standard modules

4-2-1 Time&detetime
Time-related operations, time is represented in three ways:
Timestamp after January 1, 1970 seconds, i.e.: Time.time ()
Formatted string 2016-8-23 11:11, i.e.: Time.strftime ('%y-%m-%d ')
Structured time tuples include: year, day, week, and so on. Time.struct_time namely: Time.localtime ()

Learning Essentials:

获取当前系统时间

print (time.ctime()) 

## 将字符串转换成日期格式

str_to_date  = datetime.datetime.strptime( "2016-02-01" "%Y-%m-%d" ) print (str_to_date)   # 输出=>2016-02-01 00:00:00

## 比现在快5天,(如果是慢5天用减号)

new_date  = datetime.datetime.now()  + datetime.timedelta(days = 5 ) print (new_date)

## 比现在快5小时(hours)

new_date  = datetime.datetime.now()  + datetime.timedelta(hours = 10 ) print (new_date)     ## 比现在快100秒(seconds) new_date  = datetime.datetime.now()  + datetime.timedelta(seconds = 120 ) print (new_date)4-2-2 Random---Generate stochastic numbers

Import Random
Checkcode = ' '
For I in range (4):
Current = Random.randrange (0,4)
If current! = I:
temp = Chr (Random.randint (10,100))
Else
temp = Random.randint (0,9)
Checkcode + = str (temp)
Print (Checkcode)

4-2-3 OS Module

OS.GETCWD () Gets the current working directory, which is the directory path of the current Python script work
Os.chdir ("dirname") changes the current script working directory, equivalent to the shell CD
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 (' dirname ') delete the single-level empty directory, if the directory is not empty can not be deleted, error, equivalent to the shell rmdir dirname
Os.listdir (' dirname ') lists all files and subdirectories in the specified directory, including hidden files, and prints 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 "\ \", Linux for "/"
OS.LINESEP output The line terminator used by the current platform, win under "\t\n", Linux "\ n"
OS.PATHSEP output string for splitting the file path
The Os.name output string indicates the current usage platform. Win-> ' NT '; Linux-> ' POSIX '
Os.system ("Bash command") runs a shell command that directly displays
Os.environ Getting system environment variables
Os.path.abspath (path) returns the absolute path normalized by path
Os.path.split (path) splits path into directory and file name two tuples returned
Os.path.dirname (path) returns the directory of path. is actually the first element of Os.path.split (path)
Os.path.basename (Path) 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, false if path does not exist
Os.path.isabs (path) returns True if path is an absolute path
Os.path.isfile (path) returns True if path is a file that exists. otherwise returns false
Os.path.isdir (path) returns True if path is a directory that exists. otherwise returns false
Os.path.join (path1[, path2[, ...]) returns a combination of multiple paths, and 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

4-2-4 SYS Module

SYS.ARGV command line argument list, the first element is the path of the program itself
Sys.exit (n) exit program, Exit normally (0)
Sys.version get version information for Python interpreter
Sys.maxint the largest int value
Sys.path returns the search path for the module, using the value of the PYTHONPATH environment variable when initializing
Sys.platform returns the operating system platform name
Sys.stdout.write (' please: ')
val = Sys.stdin.readline () [:-1]


4-2-5 shutil Module----Advanced file, folder, compression package processing module

--1--shutil.copyfileobj (FSRC, fdst[, length])----
Copy the contents of the file to another file, which can be part of the content

def copyfileobj (FSRC, FDST, length=16*1024):
"" "Copy data from File-like object FSRC to File-like object Fdst" "
While 1:
BUF = fsrc.read (length)
If not BUF:
Break
Fdst.write (BUF)

--2--shutil.copyfile (SRC, DST)----
Copy file: Shutil.copyfile (src= "D:\WorkSpace\day6\\test1.txt", dst= "D:\WorkSpace\day6\\test2.txt")

--3--Shutil.copystat (SRC, DST)----

Information on the status of the copy, including: mode bits, Atime, mtime, Flags

Shutil.copystat (src=,dst=)

--4--shutil.copy (SRC, DST)-----
Copying files and Permissions

Shutil.copy (SRC, DST)

--5--shutil.ignore_patterns (*patterns)
Shutil.copytree (SRC, DST, symlinks=false, Ignore=none)-----
Recursive de-Copying files


--6--shutil.rmtree (path[, ignore_errors[, onerror])----
To delete a file recursively

--7--shutil.move (SRC, DST)----
To move a file recursively

--8--shutil.make_archive (base_name, Format,...) ----

Create a compressed package and return the file path, for example: Zip, tar

Base_name: The file name of the compressed package, or the path to the compressed package. Only the file name is saved to the current directory, otherwise saved to the specified path,
For example: www + = Save to Current path
such as:/users/wupeiqi/www = Save to/users/wupeiqi/
Format: Compressed package type, "Zip", "tar", "Bztar", "Gztar"
Root_dir: Folder path to compress (default current directory)
Owner: User, default Current user
Group: Groups, default current group
Logger: Used to log logs, usually logging. Logger Object

--9--shutil Processing of compressed packets is done by calling the ZipFile and tarfile two modules----

Import ZipFile

# compression
z = zipfile. ZipFile (' Test.zip ', ' W ')
Z.write (' A.log ')
Z.write (' Data.data ')
Z.close ()

# Unzip
z = zipfile. ZipFile (' Laxi.zip ', ' R ')
Z.extractall ()
Z.close ()

Import Tarfile

# compression
tar = Tarfile.open (' Your.tar ', ' W ')
Tar.add (' Workspace/day5/test.zip ', arcname= ' Test.zip ')
Tar.add (' Workspace/day5/test1.zip ', arcname= ' Test1.zip ')
Tar.close ()

# Unzip
tar = Tarfile.open (' Your.tar ', ' R ')
Tar.extractall () # can set the decompression address
Tar.close ()

4-2-6 Shelve Module

This module is a simple k,v module that persists memory data through a file, and can persist any Python data format that pickle can support.

Import shelve

D = Shelve.open (' shelve_test ') #打开一个文件

Class Test (object):
def __init__ (self,n):
SELF.N = n


t = Test (123)
T2 = Test (123334)

name = ["Alex", "Rain", "Test"]
d["Test"] = name #持久化列表
d["T1"] = t #持久化类
d["t2"] = T2

D.close ()

4-2-7 XML

XML is a protocol that implements data exchange between different languages or programs, similar to JSON

XML protocols are supported in each language, and in Python you can manipulate XML with the following modules

Import Xml.etree.ElementTree as ET

# Parse XML file
Tree = Et.parse ("Test.xml")
# get Root
root = Tree.getroot ()
Print (Root.tag)

# Traverse XML Document
For child in Root:
Print (Child.tag, child.attrib)
For I in the child:
Print (I.tag, i.text)

# Traverse only the year node
For I in Root.iter ("year"):
Print (I.tag, i.text)


# Modify and delete XML files
Tree = Et.parse ("Test2.xml")
root = Tree.getroot ()

Second, the Python study of the Regular:

'. ' default match any character except \ n, if flag Dotall is specified, matches any character, including line break
The ' ^ ' matches the beginning of the character, and if you specify the flags MULTILINE, this can also be matched on (r "^a", "\nabc\neee", Flags=re. MULTILINE)
' $ ' matches the end of the character, or E.search ("foo$", "BFOO\NSDFSF", Flags=re. MULTILINE). Group () can also
' * ' matches the character before the * number 0 or more times, Re.findall ("ab*", "Cabb3abcbbac") results for [' ABB ', ' ab ', ' a ']
' + ' matches the previous character 1 or more times, Re.findall ("ab+", "Ab+cd+abb+bba") results [' AB ', ' ABB ']
'? ' matches a previous character 1 or 0 times
' {m} ' matches the previous character m times
' {n,m} ' matches the previous character N to M times, Re.findall ("ab{1,3}", "ABB ABC abbcbbb") Results ' ABB ', ' AB ', ' ABB ']
' | ' match | left or | Right character, re.search ("abc| ABC "," ABCBABCCD "). Group () result ' ABC '
' (...) ' Group match, Re.search ("(ABC) {2}A (123|456) C", "abcabca456c"). Group () Results abcabca456c
' \a ' matches only from the beginning of the character, Re.search ("\aabc", "ALEXABC") are not matched
' \z ' matches the end of the character, same as $
' \d ' matches the number 0-9
' \d ' matches non-numeric
' \w ' match [a-za-z0-9]
' \w ' matches non-[a-za-z0-9]
' s ' matches whitespace characters, \ t, \ n, \ r, Re.search ("\s+", "Ab\tc1\n3"). Group () result ' \ t '

‘(? P<name&gt, ...) ' Group Matching Re.search (? P<province>[0-9]{4}) (? P<city>[0-9]{2}) (? P&LT;BIRTHDAY&GT;[0-9]{4}) "," 371481199306143242 "). Groupdict (" city ") result {' Province ': ' 3714 ', ' City ': ' Bayi ', ' birthday ' : ' 1993 '}


    

Beginner Python's 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.