---
title: "python 实用技巧"
author: "teder"
date: "2011-06-20T13:39:16Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-06-20T13:45:27Z"
id: 1098426
url: "https://jifa.iteye.com/blog/1098426"
---

- python 连接GBK mysql数据库

```
#!/usr/bin/python
#coding:utf-8
import MySQLdb
fconn = MySQLdb.connect(host='freeshop.dbm.hz1.koubei.com',user='freedian',passwd='8129927@freedian',db='freedian',charset='utf8')
fcursor = fconn.cursor()
......
fcurosr.close()
fconn.close()
```

- 异常捕获

```
try:
   ...
except Exception,e:
   ...
```

 

- 中文转换

```
s.encode('gbk')
```

 

- excel操作

```
writer=csv.writer(file('building.csv','wb'))
writer.writerow([r[0],r[1]])

reader = csv.reader(file('brokerresource.csv', 'rb'))
for line in reader:
       if None==line or line[0]==None:
                   continue
       else:
                   print line[0]
```

 

- file操作

```
f = open("building_suggest.txt","w+")
 f.write(str(r[1]))
 f.write("\n")
```