zoukankan      html  css  js  c++  java
  • Python介绍

    主要内容

    1、Python安装
    2、标准输出
    3、字符串格式化
    4、数据表达
    5、内置函数
    6、输入与输出
    7、模块

    1、Python安装

    windows

     安装路径

        默认安装路径:F:Python
     设置配置环境变量
        【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
        如:原来的值;F:Python,切记前面有分号
    linux
     自带Python3.7.5
      python环境搭建参考:http://www.runoob.com/python/python-install.html
    2、标准输出
    window
    print ("Hello word!")
     
    linux
    创建文件HW.python

    [root@localhost ~]# more HW.py
    #!/bin/env python3
    #-*- coding:utf-8 -*-

    print ("hello word1")
    [root@localhost ~]# python HW.py
    hello word1

    3、字符串格式化

    字符串的方法及其注释

    capitalize()把字符串的第一个字符改为大写
    casefold()把整个字符串的所有字符改为小写
    lower()转换字符串中所有大写为小写
    center(width)将字符串居中,并使用空格填充至长度width的新字符串
    count(sub[,start[,end]])返回sub在字符串中出现的次数,start和end参数表示范围,可选
    encode(encoding='utf-8',error='strict')以encoding指定的编码格式对字符串进行编码
    endswith(sub[,start[,end]])检查字符串是否以sub结尾,是返回True、否返回False,start和end参数表示范围,可选
    startwith(prefix[,start[,end]])检查字符串是否以sub开头,是返回True、否返回False,start和end参数表示范围,可选
    expendtabs([tabsize=8])将字符串中的tab符号(	)转换为空格,默认空格数tabsize=8,可不指定
    find(sub[,start[,end]])从左向右查找,检查字符串是否含有sub,是返回索引值、否返回-1,start和end参数表示范围,可选
    rfind(sub[,start[,end]])从右向左查找,检查字符串是否含有sub,是返回索引值、否返回-1,start和end参数表示范围,可选
    index(sub[,start[,end]])从左向右查找,检查字符串sub的索引值,是返回索引值、否返回异常,start和end参数表示范围,可选
    rindex(sub[,start[,end]])从右向左查找,检查字符串sub的索引值,是返回索引值、否返回异常,start和end参数表示范围,可选
    isalnum()如果字符串至少有一个字符并且所有字符都是字母或者数字则返回True、否返回False
    isalpha()如果字符串至少有一个字符并且所有字符都是字母、则返回True、否返回False
    isdecimal()如果字符串只包含十进制数字、则返回True、否返回False
    isdigit()如果字符串只包含数字、则返回True、否返回False
    islower()如果字符串至少有一个区分大小写的字符,并且这些字符都是小写、则返回True、否返回False
    isupper()如果字符串至少有一个区分大小写的字符,并且这些字符都是大写、则返回True、否返回False
    isnumeric()如果字符串只包含数字字符、则返回True、否返回False
    isspace()如果字符串只包含空格、则返回True、否返回False
    istitle()如果字符串是标题化(所有字母的单词都以大写开始,其余字母均为小写)则返回True、否返回False
    title()返回标题化的字符串(所有字母的单词都以大写开始,其余字母均为小写)
    join(sub)以字符串作为分隔符,插入到sub中所有的字符之间
    ljust(width)返回左对齐的字符串,并且使用空格填充至长度width的新字符串
    partition(sub)从左向右查找,找到子字符串sub,把字符串分成一个3元组(pre_sub,sub,fol_sub),如果字符串不包含sub则返回('原字符串',"")
    rpartition(sub)从右向左查找,找到子字符串sub,把字符串分成一个3元组(pre_sub,sub,fol_sub),如果字符串不包含sub则返回('原字符串',"")
    replace(old,new[,count])字符串替换,如果count指定则最大替换次数为count次
    rjust(width)返回一个右对齐的字符串,并使用空格填充至长度width的新字符串
    rstrip()删除字符串末尾的空格
    lstrip()去掉字符串开头的所有空格
    strip([chars])删除字符串前后的所有空格,char参数可以定制删除的字符,可选
    swapcase()翻转字符串中的大小写
    upper()转换字符串中的所有小写字符为大写
    traslate(table)根据table的规则(可以有str.maketrans('a','b')定制)转换字符串中的字符
    zfill(width)返回长度为width的字符串,原字符串右对齐前方使用0填充
    split(sep=None,maxslit=-1)不带参数默认是以空格为分隔符切片字符串,如果maxslit有设置,则仅分割maxslit个子字符串,返回切片后的子字符串拼接的列表
    splitlines((([keepends])))按照'
    '分割,返回一个包含各行作为元素的列表,如果指定keepends则返回前keepends行

    格式化:format
    位置参数---

    >>> "{0} love {1}.{2}".format ("I","fish","com")
    'I love fish.com'

    关键字参数---

    >>> "{a} love {b}.{c}".format (a="I",b="fish",c="com")
    'I love fish.com'

    综合位置参数和关键字参数---

    >>> "{0} love {b}.{c}".format ("I",b="fish",c="com")
    'I love fish.com'

    注意:位置参数在前
    >>> "{a} love {0}.{c}".format (a="I","fish",c="com")
    SyntaxError: positional argument follows keyword argument
    注释:
    >>> "{{0}}".format ("不打印")
    '{0}'
    格式化符号“:”,表示格式化的开始
    保留小数点后一位小数:

    >>> '{0:.1f}{1}'.format(27.658,'GB')
    '27.7GB'

    保留小数点后两位小数:

    >>> '{0:.2f}{1}'.format(27.658,'GB')
    '27.66GB'

    字符串格式化符号含义
    %c格式化字符及ASCII码

    >>> '%c %c' % (97,98)
    'a b'

    %s格式化字符串

    >>> '%s' % 'I love fish .com '
    'I love fish .com '

    %d格式化整数

    >>> '%d + %d = %d' % (4,5,4+5)
    '4 + 5 = 9'

    %o格式化无符号八进制数(转换成八进制数)

    >>> '%o' % 10
    '12'

    %x格式化无符号十六进制数(转换成十六进制数)

    >>> '%x' % 160
    'a0'

    %X格式化无符号十六进制数(大写)(转换成十六进制数)

    >>> '%X' % 160
    'A0'

    %f格式化定点数,可指定小数点后的精度(默认六位)

    >>> '%f' % 27.3242
    '27.324200'

    %e用科学计数法格式化定点数

    >>> '%e' % 27.3242
    '2.732420e+01'

    %E用科学计数法格式化定点数

    >>> '%E' % 27.3242
    '2.732420E+01'

    %g根据值的大小决定使用%f或者%e

    >>> '%g' % 27.3242127467471536125
    '27.3242'
    >>> '%g' % 162948617657141127.3242
    '1.62949e+17'

    %G根据值的大小决定使用%f或者%e

    >>> '%G' % 27.3242
    '27.3242'
    >>> '%G' % 6172461754154527.3242
    '6.17246E+15'

    格式化操作符辅助指令
    m.n m是显示的最小总宽度,n是小数点后的位数

    >>> '%5.1f' % 27.3242
    ' 27.3'
    >>> '%.1e' % 27.3242
    '2.7e+01'
    - 左对齐
    >>> '%12.1e' % 27.3242
    ' 2.7e+01'
    >>> '%-11.1e' % 27.3242
    '2.7e+01

    + 整数前面显示加号+

    >>> '%+d' % 5
    '+5'
    >>> '%-d' % 5
    '5'
    >>> '%-d' % -5
    '-5'

    # 在八进制数前面显示零‘0o’,在十六进制数显示‘0x’或者‘0X’

    >>> '%#o' % 10
    '0o12'
    >>> '%#x' % 10
    '0xa'
    >>> '%#X' % 10
    '0XA'

    0 显示的数字前面填充‘0’取代空格

    >>> '%010d' % 12
    '0000000012'
    >>> '%-010d' % 12
    '12

    字符串转义含义

    ' 单引号
    " 双引号
    a 发出系统响铃
     退格符
    
     换行符
    	 横向制表符(TAB键)
    v 纵向制表符
    
     回车符
    f 换页符
    o 八进制数代表的字符
    x 十六进制数代表的字符
     表示一个空字符
    \ 反斜杠

    4、数据表达

    列表

    列表内置函数:

    >>> dir(list)
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
    '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', 
    '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', 
    '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__',
    '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__',
    '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index',
    'insert', 'pop', 'remove', 'reverse', 'sort']
    append()追加一个元素到数组
    memeber.append(xxx)
    
    extend()追加一个数组到数组
    memeber.extend([xxx,xxx,xxx])
    
    insert()添加一个元素到指定的位置
    memeber.insert(NUM,xxx) NUM in ranger(len(member))以位置0开始
    
    remove()删除列表中的元素
    member.remove(xxx) xxx是列表member中的值
    
    del删除列表中某个位置的元素或者删除列表
    del member(xxx)xxx是member某个元素的索引
    del member 不加索引表示删除整个列表
    
    pop删除列表中某个元素,并将删除的元素返回
    member.pop(xxx)xxx表示member中的某个元素
    
    aa.append(aa.pop()) 列表不变
    
    aa[a1:a2]复制出索引值a1到a2之间的元素
    
    分片复制以及赋值区别
    分片复制表示将原列表从新分配空间,并赋值得到新列表,新列表不随原列表的改变而改变
    赋值表示将原列表的空间复制链接给新列表,新老列表指向相同的空间,新列表随原列表的改变而改变
    
    member[1,2,[3,4,5],6,7]
    3 in member[2]
    member[2][1] 返回值为4 类似C中的二位数组的表达
    
    >>> aa
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> aa.index(1,2) 从位置2开始查找,找出出现的第一个1的位置
    9
    
    reverse()将列表倒序排列
    aa.reverse()
    
    sort()排序,(默认升序,由参数reverse控制默认False)
    aa.sort()升序,或者aa.sort(reverse=False)
    aa.sort(reverse=Ture)降序
    
    排序(升序):
    
    冒泡法:
    遍历整个字符串
    arr = [23,1,25,43,3]
    for s in range(len(arr)-1):
    for i in range(len(arr)-1):
    if arr[int(i)]>arr[int(j)]:
    arr[int(i)],arr[int(j)] = arr[int(j)],arr[int(i)]
    print arr
    遍历一个list,比值交换,遍历一遍结束
    遍历len(list)次,排序完成
    sort排序:
    arr = [23,1,25,43,3]
    arr.sort()
    print arr
    
    >>> arr = [23,1,25,43,3]
    >>> print arr 
    [23, 1, 25, 43, 3]
    >>> 
    >>> arr.sort(reverse=False)
    >>> print arr 
    [1, 3, 23, 25, 43]
    >>> arr = [23,1,25,43,3] 
    >>> print arr 
    [23, 1, 25, 43, 3]
    >>> 
    >>> arr.sort(reverse=True) 
    >>> print arr 
    [43, 25, 23, 3, 1]
    其他排序问题:http://wiki.python.org/moin/HowTo/Sorting
    
    index返回索引值
    print arr.index(s)#查arr中看值为s的索引
    insert插入值
    arr.insert(1,2)在索引为1的位置插入一个值
    pop挖出一个数据,和append相反
    代码1:
    arr.append(arr.pop())#没有变化
    print arr
    
    remove 根据值来删除,只删除匹配到的第一个
    reverse 反向列出
    
    数组去重:
    arr = [23,1,25,43,3,4,65,7,2,1,3,4]
    arr_str = []
    for s in arr:
    if s not in arr_str:
    arr_str.append(s)
    print arr_str
    [root@bogon opt]# python hello.py 
    [23, 1, 25, 43, 3, 4, 65, 7, 2]

    字典

    dict简介

    dict就是key value值,索引有意义
    定义
    d = {
    'name','wd'
    }
    读取dict值
    print d['name']
    增添值
    d['age'] = 12
    修改dict值
    d['name'] = 'pc' 
    print d['name']

    字典中数据检索:

    >>> name_Dict = {'tom': 'abc123tom', 'tony': 'abc123tony', 'mery': 'abc123mery', 'rose': 'abc123rose'}
    >>> name_Dict.key()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AttributeError: 'dict' object has no attribute 'key'
    >>> name_Dict.keys()
    ['tony', 'mery', 'rose', 'tom']
    >>> name_Dict.values()
    ['abc123tony', 'abc123mery', 'abc123rose', 'abc123tom']
    >>> for key in name_Dict:
    ... print(key,name_Dict[key])
    ... 
    ('tony', 'abc123tony')
    ('mery', 'abc123mery')
    ('rose', 'abc123rose')
    ('tom', 'abc123tom')
    >>> for k,v in name_Dict.items(): 
    #数据量大时建议不要使用
    ... print(k,v)
    ... 
    ('tony', 'abc123tony')
    ('mery', 'abc123mery')
    ('rose', 'abc123rose')
    ('tom', 'abc123tom')

    5、内置函数

    filter()过滤器:

    filter(function or None, iterable)
    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true.
    >>> temp = range(10)
    >>> show = filter(odd,temp)
    >>> list(show)
    [1, 3, 5, 7, 9]
    >>> list(filter(lambda x:x%2,range(10)))
    [1, 3, 5, 7, 9]


    map()映射:

    map(func, *iterables) --> map object
    Make an iterator that computes the function using arguments from
    each of the iterables. Stops when the shortest iterable is exhausted.
    >>> list(map(lambda x:x*2,range(10)))
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

    fromkeys()

    dict.fromkeys(S,[,v]) 
    ->new dict with keys from S and values equal to v(v defaults to None).
    
    >>> diect1= {}
    >>> diect1.fromkeys((1,2,3))
    {1: None, 2: None, 3: None}
    >>> diect1.fromkeys((1,2,3),'NUM')
    {1: 'NUM', 2: 'NUM', 3: 'NUM'}
    >>> diect1.fromkeys((1,2,3),('one','two','three'))
    {1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
    >>> diect1.fromkeys((1,3),('NUM'))
    {1: 'NUM', 3: 'NUM'}
    >>> diect1.fromkeys((range(5)),(''))
    {0: '', 1: '', 2: '', 3: '', 4: ''}
    
    >>> diect1.fromkeys((range(5)),(''))
    {0: '', 1: '', 2: '', 3: '', 4: ''}
    >>> diect1 = diect1.fromkeys((range(5)),(''))
    >>> diect1
    {0: '', 1: '', 2: '', 3: '', 4: ''}
    >>> for eachkey in diect1.keys():
    print(eachkey)
    0
    1
    2
    3
    4
    >>> for eachvalues in diect1.values():
    print(eachvalues)
    赞
    赞
    赞
    赞
    赞
    >>> for eachitems in diect1.items():
    print(eachitems)
    (0, '')
    (1, '')
    (2, '')
    (3, '')
    (4, '')
    
    >>> print (diect1.get(32,'某有'))
    某有
    >>> print (diect1.get(32))
    None
    
    检查成员资格(在字典中检查的是key,在序列中检查的是values)
    >>> 3 in diect1
    True
    >>> 5 in diect1
    False
    
    清空字典,将地址所对应的值清除:clear
    >>> diect1.clear()
    >>> diect1
    {}

    6、输入与输出

    输入、处理、输出

    打开文件:open
    open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream. Raise IOError upon failure.
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r' open for reading (default)
    'w' open for writing, truncating the file first
    'x' create a new file and open it for writing
    'a' open for writing, appending to the end of the file if it exists
    'b' binary mode
    't' text mode (default)
    '+' open a disk file for updating (reading and writing)
    'U' universal newline mode (deprecated)
    ========= ===============================================================
    r只读,w可写,a追加

    文件对象方法:

    f.close()关闭文件
    f.read(size=-1)从文件读取size个字符,当未给定size或者给定负值的时候,读取剩余的所有字符。然后作为字符串返回
    f.readline()以写入模式打开,如果文件存在,则在末尾追加写入
    f.write(str)将字符串str写入文件
    f.writelines(seq)向文件写入字符串序列seq,seq应该是一个返回字符串的可迭代对象
    f.seek(offset,from)在文件中移动文件指针,从from(0代表文件起始位置,1代表当前位置,2代表文件结尾)偏移offset个字节
    f.tell()返回当前在文件中的位置
    >>> f = open('c:\WiFi_Log.txt')  #打开文件
    >>> f.read() #读取文件
    "ajdhjAHD
    asfhkjaj
    'ashjfakjjfA
    '"
    >>> f.tell() #读出当前文件的位置
    >>> f.seek(12,0)  #跳到文件指定位置
    12
    >>> f.tell()
    12
    >>> f.read()
    "fhkjaj
    'ashjfakjjfA
    '"
    >>> f.seek(0,0) #回到文件起始位置
    0
    >>> list(f)
    ['ajdhjAHD
    ', 'asfhkjaj
    ', "'ashjfakjjfA
    ", "'"]
    
    注意:按行列出文件(低效率):
    >>> line = list(f)
    >>> for each_line in line:
    print(each_line)
    
    ajdhjAHD
    asfhkjaj
    'ashjfakjjfA
    '
    按行列出文件(高效率):
    >>> f.seek(0,0)
    0
    >>> for each_line in f:
    print(each_line)
    
    ajdhjAHD
    asfhkjaj
    'ashjfakjjfA
    '

    文件写入:(如果文件不存在则创建该文件)

    >>> f = open('c:\WiFi_Log.txt','w')
    >>> f.write('年后大叔加上')
    6
    >>> f.close()
    >>> f = open('c:\WiFi_Log.txt')
    >>> f.read()
    '年后大叔加上'
    >>> f = open('c:\WiFi_Log.txt','a')
    >>> f.write('年后大叔加上222')
    9
    >>> f.close()
    >>> f = open('c:\WiFi_Log.txt')
    >>> f.read()
    '年后大叔加上年后大叔加上222'

    切割文件:

    def split_file(file_name):
    f = open('file_name')
    x = []
    y = []
    count = 1
    for each_line in f :
    if each_line[:6] !='======':
    (role,line_spoken) = each_line.split(':',1)
    if role == 'XXX':
    a_x.append(line_spoken)
    if role == 'YYY':
    a_y.append(line_spoken)
    else:
    save_file(a_x,a_x,count)
    
    x = []
    y = []
    count += 1
    
    save_file(a_x,a_x,count)
    f.close()
    def save_file(a_x,a_x,count):
    file_name_x = 'x' + str(count) + '.txt'
    file_name_y = 'y' + str(count) + '.txt'
    
    x_file = open(file_name_x,'w')
    y_file = open(file_name_y,'w')
    
    x_file.writelines(a_x)
    y_file.writelines(a_y)
    
    x_file.close()
    y_file.close()
    
    split_file('file_name')

    7、模块

    模块:

    容器--->数据的封装
    函数--->语句的封装
    类--->方法和属性的封装
    模块--->程序的封装

    more hello.py
    def hi():
    print('I love fish')
    >>> import hello #加载模块的时候,只添加文件名
    >>> hi()
    Traceback (most recent call last):
    File "<pyshell#118>", line 1, in <module>
    hi()
    NameError: name 'hi' is not defined
    >>> hello.hi() #指定命名空间
    I love fish


    导入模块:

    1、import模块名
    2、from模块名import函数名
    3、import 模块名as新名字 #别名
    
    if __name__ == '__main__' #作为主程序,执行下面的操作
    搜索路径(路径由列表表示):
    默认搜索路径:
    >>> import sys
    >>> sys.path
    ['', 'F:\Python\Python35-32\Lib\idlelib', 'F:\Python\Python35-32\python35.zip', 'F:\Python\Python35-32\DLLs', 'F:\Python\Python35-32\lib', 'F:\Python\Python35-32', 'F:\Python\Python35-32\lib\site-packages']
    添加搜索路径:
    >>> sys.path.append("F:\Python\Python35-32\Lib\site-packages\test")
    >>> sys.path
    ['', 'F:\Python\Python35-32\Lib\idlelib', 'F:\Python\Python35-32\python35.zip', 'F:\Python\Python35-32\DLLs', 'F:\Python\Python35-32\lib', 'F:\Python\Python35-32', 'F:\Python\Python35-32\lib\site-packages', 'F:\Python\Python35-32\Lib\site-packages\test']

    包(package)

    1、创建一个文件夹、用于存放相关的模块,文件夹的名字即包的名字
    2、在文件夹中创建一个__init__py的模块文件,内容可以为空
    3、导入包 (import 包名.模块名 as 新名字)

    OS模块---Operating System 操作系统

    os模块中关于文件/目录常用的函数使用方法:

    >>> import os ###必须在引用OS模块之后才能正常使用
    getcwd()返回当前工作目录
    >>> os.getcwd()
    'C:\Users\admin\Desktop'
    chdir(path)改变工作目录
    listdir(path='.')列举指定目录中的文件名('.'表示当前目录,'..'表示上一级目录)
    mkdir(path)创建单层目录,如该目录已存在抛出异常
    makedirs(path)递归创建多层目录,如该目录已存在抛出异常,注意:'E:\a\b''E:\a\c'并不会冲突
    remove(path)删除文件
    rmdir(path)删除单层目录,如该目录非空则抛出异常
    removedirs(path)递归删除目录,从子目录到父目录逐层尝试删除,遇到目录非空则抛出异常
    rename(old, new)将文件old重命名为new
    system(command)运行系统的shell命令
    >>> os.system('cmd')
    walk(top)遍历top路径以下所有的子目录,返回一个三元组:(路径, [包含目录], [包含文件])【具体实现方案请看:第30讲课后作业^_^】
    以下是支持路径操作中常用到的一些定义,支持所有平台 
    os.curdir指代当前目录('.')
    os.pardir指代上一级目录('..')
    os.sep输出操作系统特定的路径分隔符(Win下为'\',Linux下为'/')
    os.linesep当前平台使用的行终止符(Win下为'
    ',Linux下为'
    ')
    os.name指代当前使用的操作系统(包括:'posix', 'nt', 'mac', 'os2', 'ce', 'java'

    os.path模块中关于路径常用的函数使用方法

    basename(path) 去掉目录路径,单独返回文件名
    >>> os.path.basename('F:\Common\plugins')
    'plugins'
    dirname(path) 去掉文件名,单独返回目录路径
    >>> os.path.dirname('F:\Common\plugins')
    'F:\Common'
    join(path1[, path2[, ...]]) 将path1, path2各部分组合成一个路径名
    >>> os.path.join('a','b','c')
    'a\b\c'
    >>> os.path.join('c:\','a','b','c')
    'c:\a\b\c'
    split(path) 分割文件名与路径,返回(f_path, f_name)元组。如果完全使用目录,它也会将最后一个目录作为文件名分离,且不会判断文件或者目录是否存在
    >>> os.path.split('F:\360\common\as.txt')
    ('F:\360\common', 'as.txt')
    >>> os.path.split('F:\360\common\asas\txt')
    ('F:\360\common\asas', 'txt')
    splitext(path) 分离文件名与扩展名,返回(f_name, f_extension)元组(####检索某个文件夹下的某一类文件)
    >>> os.path.splitext('F:\360\common\as.txt')
    ('F:\360\common\as', '.txt')
    getsize(file) 返回指定文件的尺寸,单位是字节
    getatime(file) 返回指定文件最近的访问时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
    getctime(file) 返回指定文件的创建时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
    getmtime(file) 返回指定文件最新的修改时间(浮点型秒数,可用time模块的gmtime()或localtime()函数换算)
    >>> os.path.getatime('f:\test.txt')
    1460535247.6602032
    时间格式化:
    >>> time.gmtime(os.path.getatime('f:\test.txt'))
    time.struct_time(tm_year=2016, tm_mon=4, tm_mday=13, tm_hour=8, tm_min=14, tm_sec=7, tm_wday=2, tm_yday=104, tm_isdst=0)
    >>> time.localtime(os.path.getatime('f:\test.txt'))
    time.struct_time(tm_year=2016, tm_mon=4, tm_mday=13, tm_hour=16, tm_min=14, tm_sec=7, tm_wday=2, tm_yday=104, tm_isdst=0)
    >>> time.gmtime(os.path.getmtime('f:\test.txt'))
    time.struct_time(tm_year=2016, tm_mon=4, tm_mday=13, tm_hour=8, tm_min=14, tm_sec=23, tm_wday=2, tm_yday=104, tm_isdst=0)
    >>> time.localtime(os.path.getmtime('f:\test.txt'))
    time.struct_time(tm_year=2016, tm_mon=4, tm_mday=13, tm_hour=16, tm_min=14, tm_sec=23, tm_wday=2, tm_yday=104, tm_isdst=0)
    以下为函数返回 True 或 False 
    exists(path) 判断指定路径(目录或文件)是否存在
    isabs(path) 判断指定路径是否为绝对路径
    isdir(path) 判断指定路径是否存在且是一个目录
    isfile(path) 判断指定路径是否存在且是一个文件
    islink(path)判断指定路径是否存在且是一个符号链接
    ismount(path)判断指定路径是否存在且是一个挂载点
    samefile(path1, paht2)判断path1和path2两个路径是否指向同一个文件

     

  • 相关阅读:
    求最短路径的三种算法: Ford, Dijkstra和Floyd
    Huffman树与编码
    Logistic回归模型和Python实现
    LibSVM for Python 使用
    支持向量机原理
    朴素贝叶斯分类器及Python实现
    Http协议简介
    介绍50个 WordPress 动作挂钩
    决定如何开发你的WordPress主题框架
    WordPress 主题框架是如何工作的
  • 原文地址:https://www.cnblogs.com/feiyu_Team/p/5962577.html
Copyright © 2011-2022 走看看