python学习

danny posted @ 2012年8月16日 07:31 in python with tags code python , 2017 阅读

案例法确实值得称赞,虽然是“笨办法”,一字不差,没有任何含糊,不过它确实有效,那么它就不笨。

因欲写个重命名的工具(其实之前有用shell写过),后来觉得代码相当ugly,想换个方式来实现它。尝试过perl, 无奈,熟悉正则表达式的我表示无力,太不人性了(也许我要被喷了,^_^),于是转向python,。之前有接触过,教材不对,学习方法不对,我还没入门就撤退了。现在我选择“笨办法”,也确实学到点东西了。

下面是参考另人的代码写的一个小工具,实现操作:连接oracle数据库,导出列,以某一列为原始文件名,另外一列为新文件名,批量重命名文件,并移动到目标路径。

网上查过,移动文件python的效率不高,我就改用了系统命令 move, 在传递参数时,也许会造成困扰,不过我之前刚好看过c语言传递参数(先用sprintf把命令及参数存到一个变量,然后那个变量作为参数传入system())我也照着去做,实现了参数传递,程序是相通的。

说明:@foo 其中,foo是实例名。

 

import sys
import os
from os.path import exists
import cx_Oracle
import py2exe

reload(sys)
sys.setdefaultencoding('utf-8')

def getdata(chah):
     try:
         conn = cx_Oracle.connect("system/foo@foo")
         try:
             cur = conn.cursor()
             sql = """select yh,imgname from foo where 
             chah='%s' order by yh""" % chah
             cur.execute(sql)
             allData = cur.fetchall()
         finally:
             cur.close()
             conn.close()
     except Exception, e:
         print '数据库错误:', e
         return

     for rec in allData:
         oldname = "%s.jpg" %rec[0]
         newname = rec[1]
         if exists(oldname) and not exists(newname):
            os.rename(oldname,newname) 
            print "%s => %s" %(oldname, newname)
         else:
             return 0

print "\nchah ?(quit: input q and hit ENTER)"
chah = raw_input(">")
while chah != 'q':
     print "Running..."
     getdata(chah)
     target = "d:\%s" % chah
     action = "move *.jpg %s" % target
     os.system(action)
     print "\nchah is %s" % chah
     print "\nchah ?(quit: input q and hit ENTER)"
     chah = raw_input(">")

关于连接oracle数据库,遇到一些问题,着实花了我不少时间,幸好网上都有答案,感谢国家,感谢党,感谢人民,感谢google.

不说遇到的问题,就说怎么做吧。

python版本 2.7

oracle 版本 9.2.0.4

先下载两个文件

1、cx_Oracle-5.1.2-10g.win32-py2.7.msi

2、instantclient-basic-win32-10.2.0.4.zip 这是从oracle官网下载的,坑人啊,33+M, 还非常难下载!幸好有离线服务器,再次感谢……

 

第一步,安装cx_Oracle-5.1.2-10g.win32-py2.7.msi

第二步,从instantclient-basic-win32-10.2.0.4.zip解压oraocci10.dll、oci.dll、oraociei10.dll放到C:\Python27\Lib\site-packages

第三步,设定环境变量我懒得去分析了,直接上配置

系统变量  

NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK

ORACLE_HOME=D:\oracle\ora90

路径PATH

D:\oracle\ora90\bin;D:\oracle\ora90\Apache\Perl\5.00503\bin\mswin32-x86;C:\Program Files\Oracle\jre\1.1.8\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%JAVA_HOME%\bin;C:\Program Files\Vim\vim73;d:\php5;D:\bin;C:\Program Files\MySQL\MySQL Server 5.5\bin\;d:\php5;D:\php5\ext;d:\nginx;C:\Program Files\SMPlayer\mplayer;c:\mingw\bin;C:\Python27\Lib


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter