zoukankan      html  css  js  c++  java
  • python常用函数分类整理

    python 文件操作

    python:目录与文件操作
    os.listdir(dirname):列出dirname下的目录和文件
    os.getcwd():获得当前工作目录
    os.curdir:返回但前目录('.')
    os.chdir(dirname):改变工作目录到dirname

    os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
    os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
    os.path.exists(name):判断是否存在文件或目录name
    os.path.getsize(name):获得文件大小,如果name是目录返回0L
    os.path.abspath(name):获得绝对路径
    os.path.normpath(path):规范path字符串形式
    os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
    os.path.splitext():分离文件名与扩展名
    os.path.join(path,name):连接目录与文件名或目录
    os.path.basename(path):返回文件名
    os.path.dirname(path):返回文件路径

    >>> import os
    >>> os.getcwd()
    'C:\\Python25'

    >>> os.chdir(r'C:\temp')
    >>> os.getcwd()
    'C:\\temp'

    >>> os.listdir('.')
    ['temp.txt', 'test.py', 'testdir', 'tt']
    >>> os.listdir(os.curdir)
    ['temp.txt', 'test.py', 'testdir', 'tt']

    >>> os.path.getsize('test.py')
    38L
    >>> os.path.isdir('tt')
    True
    >>> os.path.getsize('tt')
    0L

    >>> os.path.abspath('tt')
    'c:\\temp\\tt'
    >>> os.path.abspath('test.py')
    'c:\\temp\\test.py'
    >>> os.path.abspath('.')
    'c:\\temp'
    >>>
    >>> os.path.split(r'.\tt')
    ('.', 'tt')
    >>> os.path.split(r'c:\temp\test.py')
    ('c:\\temp', 'test.py')
    >>> os.path.split(r'c:\temp\test.dpy')
    ('c:\\temp', 'test.dpy'


    >>> os.path.splitext(r'c:\temp\test.py')
    ('c:\\temp\\test', '.py')
    >>> os.path.splitext(r'c:\temp\tst.py')
    ('c:\\temp\\tst', '.py')
    >>>
    >>> os.path.basename(r'c:\temp\tst.py')
    'tst.py'
    >>> os.path.dirname(r'c:\temp\tst.py')
    'c:\\temp'

    #打开文件和进行写操作
    f=open('test.txt','w')
    f.write('hello')
    f.writelines(['hi','haha'])#多行输入
    f.close()
    #append data
    f=open('test.txt','a')
    f.write('hello')
    f.writelines(['hi','haha'])
    f.close()
    #连续写入后会自动关闭
    open('test.txt','a').write('11111\r\n')
    #把result里的元素依次填到open函数里去
    result={'hello','u'}
    exec open('test.txt') in result
    #
    selected = []                  # temp list to hold matches
    fp = open('test.txt')
    for line in fp.readlines():    # Py2.2 -> "for line in fp:"
         selected.append(line)
    del line                       # Cleanup transient variable
    #
    open('test.txt').readlines()
    file在python是一个特殊的类型,它用于在python程序中对外部的文件进行操作。在python中一切都是对象,file也不例外,file有file的方法和属性。下面先来看如何创建一个file对象:

         * file(name[, mode[, buffering]])

    file()函数用于创建一个file对象,它有一个别名叫open(),可能更形象一些,它们是内置函数。来看看它的参数。它参数都是以字符串的形式传递的。name是文件的名字。
    mode 是打开的模式,可选的值为r w a U,分别代表读(默认) 写 添加支持各种换行符的模式。用w或a模式打开文件的话,如果文件不存在,那么就自动创建。此外,用w模式打开一个已经存在的文件时,原有文件的内容会被清 空,因为一开始文件的操作的标记是在文件的开头的,这时候进行写操作,无疑会把原有的内容给抹掉。由于历史的原因,换行符在不同的系统中有不同模式,比如 在 unix中是一个\n,而在windows中是‘\r\n’,用U模式打开文件,就是支持所有的换行模式,也就说‘\r’ '\n' '\r\n'都可表示换行,会有一个tuple用来存贮这个文件中用到过的换行符。不过,虽说换行有多种模式,读到python中统一用\n代替。在模式 字符的后面,还可以加上+ b t这两种标识,分别表示可以对文件同时进行读写操作和用二进制模式、文本模式(默认)打开文件。
    buffering如果为0表示不进行缓冲;如果为1表示进行“行缓冲“;如果是一个大于1的数表示缓冲区的大小,应该是以字节为单位的。

    file对象有自己的属性和方法。先来看看file的属性。

         * closed #标记文件是否已经关闭,由close()改写
         * encoding #文件编码
         * mode #打开模式
         * name #文件名
         * newlines #文件中用到的换行模式,是一个tuple
         * softspace #boolean型,一般为0,据说用于print


    file的读写方法:

         * F.read([size]) #size为读取的长度,以byte为单位
         * F.readline([size])
           #读一行,如果定义了size,有可能返回的只是一行的一部分
         * F.readlines([size])
           #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
         * F.write(str)
           #把str写到文件中,write()并不会在str后加上一个换行符
         * F.writelines(seq)
           #把seq的内容全部写到文件中。这个函数也只是忠实地写入,不会在每行后面加上任何东西。

    file的其他方法:

         * F.close()
           #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。如果一个文件在关闭后还对其进行操作会产生ValueError
         * F.flush()
           #把缓冲区的内容写入硬盘
         * F.fileno()
           #返回一个长整型的”文件标签“
         * F.isatty()
           #文件是否是一个终端设备文件(unix系统中的)
         * F.tell()
           #返回文件操作标记的当前位置,以文件的开头为原点
         * F.next()
           #返回下一行,并将文件操作标记位移到下一行。把一个file用于for ... in file这样的语句时,就是调用next()函数来实现遍历的。
         * F.seek(offset[,whence])
           # 将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了, whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进 行写操作时,文件操作标记会自动返回到文件末尾。
         * F.truncate([size])
           #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去

    文件创建操作

    import os

    if not os.path.exists(r'd:/URLS/'+name):
        os.makedirs(r'd:/URLS/'+name)   #创建文件


    path=r'd:/URLS/'+name+'/'
    try:

        os.remove( path+'url.txt')
        os.remove( path+'MalwareCallHome.txt')

    except WindowsError:

        pass

    Ini文件操作

    #coding=utf-8

    import ConfigParser

    def writeConfig(filename):
        config = ConfigParser.ConfigParser()
        # set db
        section_name = 'db'
        config.add_section( section_name )
        config.set( section_name, 'dbname', 'MySQL')
        config.set( section_name, 'host', '127.0.0.1')
        config.set( section_name, 'port', '80')
        config.set( section_name, 'password', '123456')
        config.set( section_name, 'databasename', 'test')
       
        # set app
        section_name = 'app'
        config.add_section( section_name )
        config.set( section_name, 'loggerapp', '192.168.20.2')
        config.set( section_name, 'reportapp', '192.168.20.3')
       
        # write to file
        config.write( open(filename, 'a') )
       
    def updateConfig(filename, section, **keyv):
        config = ConfigParser.ConfigParser()
        config.read(filename)
        print config.sections()
        for section in config.sections():
            print "[",section,"]"
            items = config.items(section)
            for item in items:
                print "\t",item[0]," = ",item[1]
        print config.has_option("dbname", "MySQL")
        print config.set("db", "dbname", "11")
        print "..............."
        for key in keyv:
            print "\t",key," = ", keyv[key]
        config.write( open(filename, 'r+') )
       
    if __name__ == '__main__':
        file_name = 'test.ini'
        writeConfig(file_name)
        updateConfig(file_name, 'app', reportapp = '192.168.100.100')
        print "end__"

    Python线程锁

    # -*- coding: UTF-8 -*-
    import thread
    from time import sleep
    lk = thread.allocate_lock()
    g_FinishCount = 0
    def loop(id):
        lk.acquire()  #申请锁
        for i in range (0,4):
            print "Thread ",id," working"
            sleep(1)
        lk.release()  #释放锁
        global g_FinishCount
        g_FinishCount = g_FinishCount + 1

    thread.start_new_thread(loop,(1,))
    thread.start_new_thread(loop,(2,))
    thread.start_new_thread(loop,(3,))
    while g_FinishCount < 3:
        sleep(1)

  • 相关阅读:
    POJ 2955 Brackets 区间DP
    POJ 3311 Hie with the Pie 最短路+状压DP
    POJ 3615 Cow Hurdles(最短路径flyod)
    hdu 3790 最短路径dijkstra(多重权值)
    poj 3254 Corn Fields 状压DP
    状压DP
    poj2411 Mondriaan's Dream 状压DP
    M: Mysterious Conch 字符串哈希
    哈希(hash)理解
    域渗透:GPP(Group Policy Preferences)漏洞
  • 原文地址:https://www.cnblogs.com/zhangfei/p/1866189.html
Copyright © 2011-2022 走看看