Python操作Excel文件

0

本文作者:分秒必争  发布于:2009-3-11  分类:Python  点击:

还是工作须要,目前还不会用到,过段时间会用到,因为现在程序开发进度还在起步阶段,为了避免以后要用没地方找,先在这里记一笔.本文转自http://blog.donews.com/limodou/archive/2005/07/09/460033.aspx

以下文中所说的模块下载地址: http://sourceforge.net/projects/pyexcelerator/

一、Excel文件读取

from pyExcelerator import *
sheets = parse_xls('d:/a.xls')

很简单,与 xlrd 不同。xlrd 需要先调用book = xlrd.open_workbook(filename)打开文档,然后再调用sh = book.sheet_by_index(i)来得到第几个sheet,然后再使用sh.cell_value(i, j)得到i行j列的单元格的值。操作多了一点。而上面的parse_xls(filename)则直接返回一个列表,每一项就是一个sheet的数据。每项是一个二元组(表名,单元格数据)。其中单元格数据为一个字典,键值就是单元格的索引(i,j)。如果某个单元格无数据,那么就不存在这个值。看似简单,但从处理上不象 xlrd 一样,可以知道每个sheet的最大行数和列数,然后进行循环。而使用 pyExcelerator 好象没有最大行数和列数,再加上空数据又不存在,因此在处理上相对麻烦一些。这样在处理上还需要注意。它与 xlrd 一样都支持 unicode ,但好象没有 xlrd 一样方便地判断单元格的类型的方法,感觉还是 xlrd 在功能上可能要强一些。当然这只是个人感觉,再加上只是看了看例子,并没有怎么使用。

二、Excel文件写入

这个才是重头。那么安装好 pyExcelerator 之后,读了 Readme.txt 之后了解到它的文档正在进行当中,因此想多了解如何使用它需要看它所带的例子,甚至看源程序。下面是我从例子中了解的如何写一个 Excel 文档需要了解的。

为了方便,在导入这个模块中使用了import *的方式。

from pyExcelerator import *

首先导入模块,然后是生成工作薄。

w = Workbook()

接着是加入一个工作表(sheet)。

ws = w.add_sheet('Hey, Dude')

然后就可以保存了。

w.save('mini.xls')

上面的代码加在一起就是:

from pyExcelerator import *

w = Workbook()
ws = w.add_sheet('Hey, Dude')
w.save('mini.xls')

这就是最小的一个例子了,在例子中叫mini.py。你可以在例子目录下运行mini.py看一看是不是生成了一个空的Excel文件。

如果想加入中文很简单,改为:

#coding=cp936
from pyExcelerator import *

w = Workbook()
ws = w.add_sheet(u'这是中文')
w.save('mini.xls')

这样上面的执行结果是生成一个空Excel文件,但它的第一个sheet的名字为“这是中文”。就这样,只要保证你写入时使用unicode就行了。

空文件可以生成,那么如何插入单元格呢?

ws.write(i, j, value)

其中value为值,可以是unicode。

接着,我们可能想改变单元格的样式,如字体:

font0 = Font()
font0.name = 'Times New Roman'
font0.struck_out = True
font0.bold = True

style0 = XFStyle()
style0.font = font0

这样我们创建了一个字体,然后又生成了一个样式。注意,真正起作用的是样式,字体不过是样式中的一种效果。

这样在写入单元格时带着这个样式就行了,还是使用上面的write()方法:

ws.write(1, 1, 'Test', style0)

这是在名为ws的sheet中的第(1,1)单元格写入了值为"Test"的内容,并且它的样式为style0。

然后我们还可以设置单元格的边框:

    borders = Borders()
    borders.left = 5
    style.borders = borders

上面创建了一个边框效果,设置了左边框,至于5是什么意思,我也不清楚,随便写的。然后放到样式中。上面的例子可以参考format.py程序。

其它还有许多的效果,简单地列一下:

 示例名 说明 
 col_width.py 改变单元格宽度 
 row_style.py 设置行的高度 
 merged*.py

单元格合并 

 image.py

插入图片 

 outline*.py

大纲效果(以前真没用过) 

 wsprops.py

sheet的属性值打印 

 xls2*.py

Excel转为其它的文件格式 

合并2个字典

0

本文作者:分秒必争  发布于:2009-3-10  分类:Python  点击:

因工作中须要编写一段程序,而从我个人的构思就是合并2个字典比较麻烦,经过在论坛一翻问答,目前已有一答案,不知道处理数据量很大的情况会不会很慢先记一笔吧

字典
            #姓名    #电话
list1 = {"aaa":"12345",
            "bbb":"76859",
            "ccc":"346843",
            "eee":"0854335"}
            #姓名    #手机
list3 = {"aaa":"1234577",
            "bbb":"7685977",
            "ddd":"3468437777",
            "eee":"085433544"}
for k,v in list1.items():
    if list3.has_key(k):
        list3[k]=list3[k]+','+v   
    else:
        list3[k]=v

print  list3

运行结果如下,懂PYTHON的人都知道,这个结果已和我要的结果非常相近了

{'eee': '085433544,0854335', 'aaa': '1234577,12345', 'bbb': '7685977,76859', 'ddd': '3468437777'}

#姓名     电话       手机
aaa         12345       1234577
bbb         76859       7685977
ccc          346843
ddd                          3468437777
eee         0854335   085433544

 

Python连接MSSqlserver

0

本文作者:分秒必争  发布于:2009-2-26  分类:Python  点击:

需要pymssql模块

模块下载地址:http://pymssql.sourceforge.net/

例子:

import pymssql
con=pymssql.connect(host='127.0.0.1',user='sa',password='',database='dbname')
cur=con.cursor()

cur.execute('select count(*) from bokewu_table')
for i in  cur.fetchall():
    for j in i
        print j #为什么这里用2次for ,是因为能让中文完整的显示,我就是因为这里少一次循环而整了半天不能显示中文
print cur.fetchall()
cur.close()
con.close()

 

ms08-067 Py检测源码

0

本文作者:分秒必争  发布于:2009-2-3  分类:Python  点击:

这是月简发给我的一个Python版的MS08-067的一个源码,一直放在自己电脑里,因为这个漏洞太恐怖了,所以没放出来,这个脚本用来检测系统是否存在MS08-067漏洞的,现在蠕虫都有了,这个东西也没有多少危险性了,也就放在网上,供大家学习用,源码如下

#!/usr/bin/env python

'''
Name: Microsoft Server Service Remote Path Canonicalization Stack Overflow Vulnerability

Description:
Anonymously check if a target machine is affected by MS08-067 (Vulnerability in Server Service Could Allow Remote Code Execution)

Author: Bernardo Damele A. G. <bernardo.damele@gmail.com>

License: Modified Apache 1.1

Version: 0.4

References:
* BID: 31874
* CVE: 2008-4250
* MSB: MS08-067
* VENDOR: http://blogs.technet.com/swi/archive/2008/10/25/most-common-questions-that-we-ve-been-asked-regarding-ms08-067.aspx
* VENDOR: http://www.microsoft.com/technet/security/advisory/958963.mspx
* MISC: http://www.phreedom.org/blog/2008/decompiling-ms08-067/
* MISC: http://metasploit.com/dev/trac/browser/framework3/trunk/modules/exploits/windows/smb/ms08_067_netapi.rb
* MISC: http://blog.threatexpert.com/2008/10/gimmiva-exploits-zero-day-vulnerability.html
* MISC: http://blogs.securiteam.com/index.php/archives/1150

Tested:
* Windows 2000 Server Service Pack 0
* Windows 2000 Server Service Pack 4 with Update Rollup 1
* Microsoft 2003 Standard Service Pack 1
* Microsoft 2003 Standard Service Pack 2 Full Patched at 22nd of October 2008, before MS08-067 patch was released

Notes:
* This check might crash the SRVSVC process on Microsoft XP Service Pack 2 and 3
'''


import select
import socket
import struct
import sys
import traceback

from optparse import OptionError
from optparse import OptionParser
from threading import Thread

try:
    from impacket import smb
    from impacket import uuid
    from impacket.dcerpc import dcerpc
    from impacket.dcerpc import transport
except ImportError, _:
    print 'ERROR: this tool requires python-impacket library to be installed, get it '
    print 'from http://oss.coresecurity.com/projects/impacket.html or apt-get install python-impacket'
    sys.exit(1)


CMDLINE = False
SILENT  = False


class connectionException(Exception):
    pass


class MS08_067(Thread):
    def __init__(self, target, port=445):
        super(MS08_067, self).__init__()

        self.__port   = port
        self.target   = target
        self.status   = 'unknown'


    def __checkPort(self):
        '''
        Open connection to TCP port to check if it is open
        '''

        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
            s.connect((self.target, self.__port))
            s.close()

        except socket.timeout, _:
            raise connectionException, 'connection timeout'

        except socket.error, _:
            raise connectionException, 'connection refused'


    def __connect(self):
        '''
        SMB connect to the Computer Browser service named pipe
        Reference: http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_browser.html
        '''

        try:
            self.__trans = transport.DCERPCTransportFactory('ncacn_np:%s[\\pipe\\browser]' % self.target)
            self.__trans.connect()

        except smb.SessionError, _:
            raise connectionException, 'access denied (RestrictAnonymous is probably set to 2)'

        except:
            #raise Exception, 'unhandled exception (%s)' % traceback.format_exc()
            raise connectionException, 'unexpected exception'


    def __bind(self):
        '''
        DCERPC bind to SRVSVC (Server Service) interface
        Reference: http://www.hsc.fr/ressources/articles/win_net_srv/msrpc_srvsvc.html
        '''

        try:
            self.__dce = self.__trans.DCERPC_class(self.__trans)

            self.__dce.bind(uuid.uuidtup_to_bin(('4b324fc8-1670-01d3-1278-5a47bf6ee188', '3.0')))

        except socket.error, _:
            raise connectionException, 'unable to bind to SRVSVC interface'

        except:
            #raise Exception, 'unhandled exception (%s)' % traceback.format_exc()
            raise connectionException, 'unexpected exception'


    def __forgePacket(self):
        '''
        Forge the malicious NetprPathCompare packet
        '''

        self.__request  = struct.pack('<HHHI', 0, 2, 1, 0)       # Point to Server Unc
        self.__request += struct.pack('<HII', 0, 1, 0)           #
        self.__request += struct.pack('<I', 46)                  # Max Count
        self.__request += struct.pack('<I', 0)                   # Offset
        self.__request += struct.pack('<I', 46)                  # Actual Count
        self.__request += struct.pack('2s78s', '\\', 'A\x00'*39) # Path1
        self.__request += struct.pack('2sHH', '\\', 46, 46)      #
        self.__request += struct.pack('2s4s', '\\', 'n')         #
        self.__request += struct.pack('<I', 3)                   # Max Count
        self.__request += struct.pack('<I', 0)                   # Offset
        self.__request += struct.pack('<I', 3)                   # Actual Count
        self.__request += struct.pack('2s4s', '\\', 'n')         # Path2
        self.__request += struct.pack('<HI', 0, 1)               # Path Type
        self.__request += struct.pack('<I', 0)                   # Path Flags


    def __compare(self):
        '''
        Compare NetprPathCompare response field 'Windows Error' with the
        expected value (WERR_OK) to confirm the target is vulnerable
        '''

        self.__vulnerable = struct.pack('L', 0)

        # The target is vulnerable if the NetprPathCompare response field
        # 'Windows Error' is WERR_OK (0x00000000)
        if self.__response == self.__vulnerable:
            self.status = 'VULNERABLE'
        else:
            self.status = 'not vulnerable'

        self.result()


    def result(self):
        if CMDLINE == True and self.status in ('VULNERABLE', 'not vulnerable'):
           print '%s: %s' % (self.target, self.status)
        elif CMDLINE == True and SILENT != True:
           print '%s: %s' % (self.target, self.status)


    def run(self):
        try:
            self.__checkPort()
            self.__connect()
            self.__bind()
        except connectionException, e:
            self.status = e
            self.result()
            return None

        # Forge and send the NetprPathCompare operation malicious packet
        self.__forgePacket()
        self.__dce.call(0x20, self.__request)

        # Get back the NetprPathCompare response and check if it is vulnerable
        self.__response = self.__dce.recv()
        self.__compare()


if __name__ == '__main__':
    CMDLINE = True

    usage = '%s [-d] {-t <target>|-l <iplist.txt>}' % sys.argv[0]
    parser  = OptionParser(usage=usage, version='0.4')
    targets = set()

    # Create command line options
    try:
        parser.add_option('-d', dest='descr', action='store_true', help='show description and exit')

        parser.add_option('-t', dest='target', help='target IP or hostname')

        parser.add_option('-l', dest='list', help='text file with list of targets')

        parser.add_option('-s', dest='silent', action='store_true', help='be silent')

        (args, _) = parser.parse_args()

        if not args.descr and not args.target and not args.list:
            print usage
            sys.exit(1)

    except (OptionError, TypeError), e:
        parser.error(e)

    descr  = args.descr
    target = args.target
    tList  = args.list

    SILENT = args.silent

    if descr:
        print __doc__
        sys.exit(0)

    if tList:
        try:
            fd = open(tList, 'r')
        except IOError:
            print 'ERROR: unable to read targets list file \'%s\'' % tList
            sys.exit(1)

        for line in fd.readlines():
            target = line.replace('\n', '').replace('\r', '')
            targets.add(target)
    else:
        targets.add(target)

    if not targets:
        print 'ERROR: no targets specified'
        sys.exit(1)

    targets = list(targets)
    targets.sort()

    for target in targets:
        current = MS08_067(target)
        current.start()

电脑搭建PyS60模拟器

0

本文作者:分秒必争  发布于:2009-1-21  分类:Python  点击:

网上摘来以下一段话:

先下载几个文件,分别是python for widonw,wxpython,S60模块.
以下文件只适合电脑上下载和安装(体积大于20m)

点此下载python(一个安装在windows环境下的版本,最新版是2.5)

点此下载wxpython(基于python环境的一个图形界面)

点此下载S60功能包(一组python模块)

文件按顺序安装:python-->>wxpython-->>解压S60功能包,将里面的文件放到python安装目录下的LIB目录里.其实这个方法并不是最好的

python和wxpython的版本是要对应的.本文所引用的都是基于python2.4版的.

安装好后,在开始->程序->里面有个Python2.4.进去运行解释器.可以命令行里输入import appuifw了.会自动弹出窗口(仿手机),把保存好的pys60脚本存为文件,在解释器里运行,该会有惊喜.至于这里的惊喜,我也不知道是指什么惊喜,我可没发现什么

结果,上面下载S60功能包的地址是错的,怎么下都下不了,自己找来了一个http://jaist.dl.sourceforge.net/sourceforge/pys60-compat/pys60-compat-0.4.tgz

配置完成后只是有的基本的模块,并不是全部的模块,要其它模块须下载 Python For S60,打开这个里面sdk_files.zip\epoc32\winscw\c\resource 这个目录下有手机的Python用的库,然后把下载的功能包和这个Python For S60 的sdk_files.zip\epoc32\winscw\c\resource 解压到同一个目录,不过一定要先解压sdk_files.zip\epoc32\winscw\c\resource ,然后再覆盖,这样不会损坏原的Python的库接下载把要调式的脚本放上面解压的目录中运行,即可,这样所有的库都在了

[原]一个多线程的小例子

0

本文作者:分秒必争  发布于:2009-1-20  分类:Python  点击:

import threading
def start():
    i = 0
    while i < 100:
        i +=1
        print i
if __name__=='__main__':
    for i in range(10):
        i = threading.Thread(target = start)
        i.start()

电脑速度快的可能在下一个线程还没开始就计算完了,你可以把    while i < 100:改成10000或者更大,等执行完了就可以看到效果了

和python有关的网址大全

0

本文作者:分秒必争  发布于:2009-1-19  分类:Python  点击:

Graphical interface wxPython http://wxpython.org
Graphical interface pyGtk http://www.pygtk.org
Graphical interface pyQT http://www.riverbankcomputing.co.uk/pyqt/
Graphical interface Pmw http://pmw.sourceforge.net/
Graphical interface Tkinter 3000 http://effbot.org/zone/wck.htm
Graphical interface Tix http://tix.sourceforge.net/




Database MySQLdb http://sourceforge.net/projects/mysql-python
Database PyGreSQL http://www.pygresql.org/
Database Gadfly http://gadfly.sourceforge.net/
Database SQLAlchemy http://www.sqlalchemy.org/
Database psycopg http://www.initd.org/pub/software/psycopg/
Database kinterbasdb http://kinterbasdb.sourceforge.net/
Database cx_Oracle http://www.cxtools.net/default.aspx?nav=downloads
Database pySQLite http://initd.org/tracker/pysqlite




MSN Messenger msnlib http://auriga.wearlab.de/~alb/msnlib/
MSN Messenger pymsn http://telepathy.freedesktop.org/wiki/Pymsn
MSN Messenger msnp http://msnp.sourceforge.net/
Network Twisted http://twistedmatrix.com/
Images PIL http://www.pythonware.com/products/pil/
Images gdmodule http://newcenturycomputers.net/projects/gdmodule.html
Images VideoCapture http://videocapture.sourceforge.net/




Sciences and Maths scipy http://www.scipy.org/
Sciences and Maths NumPy http://numpy.scipy.org//
Sciences and Maths numarray http://www.stsci.edu/resources/software_hardware/numarray
Sciences and Maths matplotlib http://matplotlib.sourceforge.net/




Games Pygame http://www.pygame.org/news.html
Games Pyglet http://www.pyglet.org/
Games PySoy http://www.pysoy.org/
Games pyOpenGL http://pyopengl.sourceforge.net/




Jabber jabberpy http://jabberpy.sourceforge.net/




Web scrape http://zesty.ca/python/scrape.html
Web Beautiful Soup http://crummy.com/software/BeautifulSoup
Web pythonweb http://www.pythonweb.org/
Web mechanize http://wwwsearch.sourceforge.net/mechanize/




Localisation geoname.py http://www.zindep.com/blog-zindep/Geoname-python/




Serial port pySerial http://pyserial.sourceforge.net/
Serial port USPP http://ibarona.googlepages.com/uspp




Parallel Port pyParallel http://pyserial.sourceforge.net/pyparallel.html




USB Port pyUSB http://bleyer.org/pyusb/




Windows ctypes http://starship.python.net/crew/theller/ctypes/
Windows pywin32 http://sourceforge.net/projects/pywin32/
Windows pywinauto http://www.openqa.org/pywinauto/
Windows pyrtf http://pyrtf.sourceforge.net/
Windows wmi http://timgolden.me.uk/python/wmi.html




PDA/GSM/Mobiles pymo http://www.awaretek.com/pymo.html
PDA/GSM/Mobiles pyS60 http://sourceforge.net/projects/pys60




Sound pySoundic http://pysonic.sourceforge.net/
Sound pyMedia http://pymedia.org/
Sound FMOD http://www.fmod.org/
Sound pyMIDI http://www.cs.unc.edu/Research/assist/developer.shtml




GMail libgmail http://libgmail.sourceforge.net/
Google pyGoogle http://pygoogle.sourceforge.net/
Expect pyExpect http://pexpect.sourceforge.net/
WordNet pyWordNet http://osteele.com/projects/pywordnet/
Command line cmd http://blog.doughellmann.com/2008/05/pymotw-cmd.html
Compiler backend llvm-py http://mdevan.nfshost.com/llvm-py/
3D VPython http://vpython.org

python模块之zipfile

0

本文作者:分秒必争  发布于:2009-1-19  分类:Python  点击:

转自:http://blog.csdn.net/zhaoweikid/archive/2007/05/30/1630842.aspx

zipfile是python里用来做zip格式编码的压缩和解压缩的,由于是很常见的zip格式,所以这个模块使用频率也是比较高的,在这里对zipfile的使用方法做一些记录。即方便自己也方便别人。
zipfile里有两个非常重要的class, 分别是ZipFile和ZipInfo, 在绝大多数的情况下,我们只需要使用这两个class就可以了。ZipFile是主要的类,用来创建和读取zip文件而ZipInfo是存储的zip文件的每个文件的信息的。
    比如要读取一个zipfile,这里假设filename是一个文件的路径:


 

import zipfile

= zipfile.ZipFile(filename, 'r'# 这里的第二个参数用r表示是读取zip文件,w是创建一个zip文件

for f in z.namelist():
    
print f



    上面的代码是读取一个zip压缩包里所有文件的名字。z.namelist() 会返回压缩包内所有文件名的列表。
再看看下面一个:

 

import zipfile

= zipfile.ZipFile(filename, 'r')

for i in z.infolist():
    
print i.file_size, i.header_offset


   
    这里使用了z.infolist(), 它返回的就是压缩包内所有文件的信息,就是一个ZipInfo的列表。一个ZopInfo对象中包含了压缩包内一个文件的信息,其中比较常用的是 filename, file_size, header_offset, 分别为文件名,文件大小,文件数据在压缩包中的偏移。其实之前的z.namelist()就是读取的ZopInfo中的filename,组成一个 list返回的。
从压缩包里解压缩出一个文件的方法是使用ZipFile的read方法:

 

import zipfile

= zipfile.ZipFile(filename, 'r')

print z.read(z.namelist()[0])



这样就读取出z.namelist()中的第一个文件,并且输出到屏幕,当然也可以把它存储到文件。

下面是创建zip压缩包的方法:

与读取的方法其实很类似的:

 

import zipfile, os

= zipfile.ZipFile(filename, 'w'# 注意这里的第二个参数是w,这里的filename是压缩包的名字

#假设要把一个叫testdir中的文件全部添加到压缩包里(这里只添加一级子目录中的文件):
if os.path.isdir(testdir):
    
for d in os.listdir(testdir):
        z.write(testdir
+os.sep+d)
# close() 是必须调用的!
z.close()



上面的代码非常的简单。
想想还有一个问题,如果我把一个test/111.txt 添加到压缩包里之后我希望在包里它放到test22/111.txt怎么办呢?
其实这个就是ZipFile的write方法中第二个参数的作用了。只需要这样调用:z.write("test/111.txt", "test22/111.txt") 

[原]python版修改环境变量

0

本文作者:分秒必争  发布于:2009-1-15  分类:Python  点击:

代码如下:

import win32api,win32con,os
key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,'SOFTWARE\\Python\\PythonCore\\2.5\\InstallPath',0, win32con.KEY_ALL_ACCESS)
value = win32api.RegQueryValue(key,'')
print u'原Path环境变量是\n%s' % os.environ["Path"]
os.environ["Path"] = value[0:-1] +';'+os.environ['Path']
print u'现Path环境变量是\n%s' % os.environ["Path"]
 

自动读取python的安装目录并将其加入环境变量,有一个问题就是重启python环境,此环境变量会失效.本来想通过修改注册表的方法实现,但要重启电脑才能生效,先放一个吧

[python] 简单说说set类型

0

本文作者:分秒必争  发布于:2009-1-13  分类:Python  点击:

转自:http://hi.baidu.com/smallfish7788/blog/item/271ab534b599168ca61e12f4.html

set也是python里一个重要类型,有时候还是蛮好用的。详细文档和说明可以用help(set) 查看其说明和方法。

下面来点简单的小例子说明把。

>>> x = set('spam')
>>> y = set(['h','a','m'])
>>> x, y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))

再来些小应用。

>>> x & y # 交集
set(['a', 'm'])

>>> x | y # 并集
set(['a', 'p', 's', 'h', 'm'])

>>> x - y # 差集
set(['p', 's'])

记得以前个网友提问怎么去除海量列表里重复元素,用hash来解决也行,只不过感觉在性能上不是很高,用set解决还是很不错的,示例如下:

>>> a = [11,22,33,44,11,22]
>>> b = set(a)
>>> b
set([33, 11, 44, 22])
>>> c = [i for i in b]
>>> c
[33, 11, 44, 22]

很酷把,几行就可以搞定。

 

Page 2 of 7 «1234567»