Original works, allow reprint, reprint, please be sure to hyperlink form to indicate the original source of the article, author information and this statement. Otherwise, legal liability will be held. Http://blog.csdn.net/github_27109687/article/details/73850886-Test_huhy Blog
The module is actually a python file. The import module (whether using the ' Import module ' or ' From module import xxx ') is essentially a if__name__= ' __main ' code that executes everything in the module from beginning to end. first, the concept of the import module
# (1) for the same directory:
#前提: The day file has the product module and model is the module. Run is a function in the model module, name is the variable in model file
import model
model.run ()
print (model.name)
# Import the model.py file in the same directory in the product module, use ' Model.run () ' If you call the Run function, or use ' model.name ' if you call the name variable, such as: Print (Model.name)
from model import run
run ()
#如果在product模块导入同一个目录下model里的run函数的话, direct use of ' run () ' from
model import *
run ()
#product模块从同一个目录下的model里导入所有的函数, keep in mind that this method is used sparingly, because multiple modules are used so that it is not easy to find the module in which the function resides. If you use the Run function, use the ' run () ' from
model import name
print (name)
#product模块导入同一个目录下model里的name变量 directly, The name can be used directly, such as: print (name)
# (2) for different directories:
#前提是: Under the Day1 and day two directories under the project, the Day1 has a CMS module, the module has HHH () function and User_ filename variable; Day has the product module from
day1 import CMS
cms.hhh ()
#或者 from
day1. CMS Import HHH
hhh ()
#day下的product模块里导入day1下模块里的hhh函数 from
day1. CMS Import user_filename
print (user_filename)
#day下的product模块里导入day1下模块里user_filename变量
second, Python's environment variables
Environment variables are used to allow users to run commands (for example, Python) in any directory. When you import a module, Python first finds the module in the current directory, and if the file is not found in the current directory, then go to the environment variable to find the directory. Run in Pycharm, the default will be 2 directory paths into the Python environment path, one is the current directory, the other is the current project directory, however, in the CMD command run or server run, you need to manually add the directory to the environment variables, otherwise you will not find the module. Therefore, it is best to add the current project directory to the environment variable.
Remember that the Python code runs and the path to the environment variable is automatically removed.
Import sys
Sys.path.insert (0,r ' xxxx ') # ' XXXX ' is the path address
three, random module
Import Random
print (Random.random ()) #获取随机浮点数, default to 0-1, cannot specify range
print (Random.uniform (1,34)) #获取随机浮点数, you can specify a range
Print (Random.randint (1,366)) #随机取整数, you can specify a range
of print (Random.randrange (1,366)) #随机取整数, you can specify a range of
print ( Random.choice ([' X45yqty ', 5,7, ' a ')) #随机从可迭代对象里去一个元素
print (random.sample (' X45yqty ', 5,7, ' a ', 89,6), 3)] # Randomly take several elements from the iteration object, return the tuple
x=[1,2,3,4,5,7,8,10, ' Aty ']
random.shuffle (x) #洗牌, disturb the order of the original list, will change the original list value
print ( X
Four, string module
#string模块
Import string
print (string.ascii_letters) #获取所有的大小写字母, returns a string of
print (string.ascii_ lowercase) #获取所有的小写字符, returns the string print
(string.ascii_uppercase) #获取所有的大写字符, returns the string
print (string.digits) #获取所有的数字, return string
Five, JSON module
Both the dictionary and list types can be formatted through JSON. JSON is also a data type, and it also has a list and a dictionary.
#json. Loads () method, examples are as follows:
import json,requests
url= ' http://video.tudou.com/subscribe/check?uid= undy1njiwndkwna%3d%3d&_=1498723117672 '
res=requests.get (URL). text
print (type (res))
res_ll= Json.loads (res) #json串转为字典
print (Type (RES_LL)
#json. Load () method, as the following example:
import JSON
fr=open (' Asg.json
New_res=json.load (FR)
#把文件里的json串转换成字典, the Load method passes in a file object, and then the load method automatically reads the contents of the file and then turns to the dictionary
print (new_ RES)
print (Type (new_res))
#json. Dumps () method, as the following example:
import json
dic={
' username ': ' Huhy ',
' age ': Sex '
: ' Female '
}
dic_j=json.dumps (DIC) #字典转成json字符串
print (dic_j)
print (type (Dic_j))
#json. Dump () method, examples are as follows:
import JSON
dic={
' username ': ' huhy ',
' age ': '
sex ': ' Woman '
}
fw=open (' Zzh ', ' W ')
json.dump (DIC,FW) #操作文件, turn the dictionary into a string and write it directly into the file.
Six, Time/datetime module
Time has three kinds of formats: the first is the timestamp, the second is the format time, and the third is the time tuple
Import Time,datetime
time.sleep (1) #程序休息几秒
print (Time.time ()) #获取当前时间戳
print (Time.localtime ( 1497950139)) #获取时间元组, where 1497950139 is the timestamp, and the default is the current time zone utc+8
print (Time.localtime ()) #时间戳不写的话, by default get the current times tuple
print ( Time.gmtime (1498732057.6223967)) #获取时间元组, the default is the Standard Time zone UTC
Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.gmtime ( 1498732057.6223967))
# #将时间元组1498732057.6223967 converted to formatted time 2017-06-29 10:27:37
print (time.strftime ("% y-%m-%d%h:%m:%s ") #时间元组不写的话, the default gets the current formatted time
print (Time.asctime ()) #将时间元组转换成格式化时间, the default current time is not written in parentheses. For example output: Fri June 14:36:57 2017
print (Time.ctime (1498732057.6223967)) #讲时间戳转换成格式化时间, the default current time is not written in parentheses. For example output: Thu June 18:27:37 2017
print (Datetime.datetime.now ()) #将当前时间格式化输出 2017-06-29
18:35:24.570104 Print (Datetime.datetime.now () +datetime.timedelta (3)) #3天后的时间
print (Datetime.datetime.now () + Datetime.timedelta ( -3)) #3天前的时间
Seven, Os/sys module
import sys print (SYS.ARGV) #获取命令行参数list, the first element is the path to the program itself, and the following element is the parameter print (sys.version) # Gets the version information print (Sys.path) #返回模块的搜索路径 of the Python interpreter, initializes the value print (Sys.platform) that uses the PYTHONPATH environment variable #返回操作系统平台名称 sys.stdout.write (' please: ') #向屏幕输出一句话, equivalent to: print (' please: ') val=sys.stdin.readline () [: -1] #获取输入的 sys.exit (0) #退出程序, exit exit (0)
Import os,time Print (OS.GETCWD ()) #获取当前工作目录, Absolute path os.chmod (' \user\bin ', 7) #linux环境下, add permissions to File/directory print (Os.chdir (R ' d:\ Learning\huhy ') #更改当前目录, to the specified directory in print (Os.makedirs ("OS/HUHY1/HAT1")) #在父目录下递归创建文件夹 print (Os.removedirs ("Os/file")) #
Delete the empty directory recursively, if not empty directory cannot delete, will error print (Os.mkdir (' Huat ')) #创建文件夹, if the folder already exists will error Os.rmdir (r "D:\learning\huhy\sample\huat") #删除文件夹 Print (Os.remove (R ' D:\learning\huhy\sample\huat\sss.txt ')) #删除文件 if the file is not found to be an error Os.rename (R ' Huat\test.txt ', R ' huat\
Case.txt ') #重命名文件的名称 print (Os.stat (R ' huat\case.txt ')) #获取文件信息 print (os.name) #显示当前使用的平台 print (OS.SEP) #当前操作系统的路径分隔符 Print (Os.environ) #当前系统的环境变量 print (OS.PATHSEP) #当前系统的环境变量中每个路径的分隔符, Linux is ', ', Windows is '; ' Print (OS.LINESEP) # Line breaks for the current operating system with open (' Huat\case.txt ', ' W ', encoding= ' Utf-8 ') as Fw:fw.write (' ddddd ') fw.write (OS.LINESEP) FW.WR The ITE (' Taayy ') print (Os.path.abspath (__file__)) #获取当前文件的绝对路径 print (__file__) #这个也会获取到当前文件的路径, but the slash inside the path does not conform to the path format print ( Os.path.split (' Huat\case.txt ')) #分割文件和路径名称 print (Os.path.dirname (R ' \usr\local\bin ')) #获取父目录 print (Os.path.Exists (R ' \usr\local\bin\a.txt ')) #判断文件目录/file exists, returns True if it exists, otherwise returns false print (Os.path.join os.path.dirname ( Os.path.abspath (__file__)), ' Huat ') #拼接成一个路径 print (Os.path.join (R ' D:\learning\huhy\sample ', ' Huat ')) #同上, splicing path print (Os.listdir ('. ')) #列出当前目录下的所有文件 Print (Os.listdir ('.. ')) #列出父目录下的所有文件 Print (Os.path.getatime (R ' D:\learning\huhy\day\login.py ')) Print (Time.strftime ("%y-%m-%d%h:%m:%s"), Time.localtime (Os.path.getatime (R ' D:\learning\huhy\day\login.py '))) #os. Path.getatime output The most recent access timestamp print ( Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Os.path.getmtime (R ' D:\learning\huhy\day\login.py '))) Os.path.getmtime Output recently modified timestamp print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (Os.path.getctime (R ' D:\learning\ huhy\day\login.py ')) #os. path.getctime output File Create timestamp print (Os.curdir) #当前目录 print (Os.pardir) #父目录 print ( Os.path.basename (R ' \usr\local\bin\a.txt ') #获取最后一级, if the file displays the filename, if the directory displays the directory name print (Os.path.isabs R ' D:\sample\huat\ Sss.txt ') #判断是否是绝对路径, is the absolute path returns TRUE, otherwise returns false print (Os.path.isfile R D:\learning\huhy\sample\huat\Case.txt ') #判断该绝对路径是否是文件 print (Os.path.isdir (R ' D:\learning\huhy\sample\huat ')) #判断是否是路径