Do things with Python (1)

Posted: July 10th, 2008 | Author: mike | Filed under: Script Language |

Python到底有多简洁、高效?

1 import glob 2 import os 3 4 files = glob.glob('/cygdrive/c/Users/Mike/Desktop/Data Export/cube_export_*.txt') 5 for file in files: 6 #get file path and file name 7 (filePath, fileName) = os.path.split(file) 8 rfile = open(file, "r") 9 wfile = open('%s\\%s%s' %(filePath, fileName, "_calculations.txt"), "w") 10 11 #get the content needed in text and write to new filE 12 for line in rfile: 13 if line.find("Statement:") > -1: 14 wfile.write(line.lstrip("Statement:").rstrip()) 15 wfile.write(";\r\n") 16 wfile.close() 17 rfile.close()

上面的代码完成了以下工作:

  1. 遍历目录下文件(注意是支持用通配符筛选文件)
  2. 打开文件
  3. 读取每行,并且过滤内容
  4. 写入新文件

下面是操作数据库的实例,我把一个表中的几个字段拼接插入到另一个表中。这里只展现了Python在格式化字符串的灵活之处。

如果用list来做,效果可能更佳。但是通过两个列子,足以看到Python的魅力所在。

1 import pymssql 2 3 conn = pymssql.connect(host='CDCVM4505', user='sa', password='sysadm', database='es0617') 4 cur = conn.cursor() 5 cur2 = conn.cursor() 6 7 query = "SELECT MemberID, Comment_Id FROM [Cell_Comment_Key_Budget2008_V2_1] ORDER BY Comment_ID" 8 cur.execute(query) 9 for x in range(cur.rowcount/10): 10 new_key = ";".join(["%s" %mid for mid, cid in cur.fetchmany(10)]) 11 query = "UPDATE [Cell_Comment_Budget2008_V2_1] SET Comment_Key = '%s' WHERE Comment_Id = %s" %(new_key, cid) 12 res = cur2.execute(query) 13 14 conn.commit() 15 conn.close()
  • Share/Save/Bookmark


Leave a Reply