python学习经验 #
Date: 2015/6/12
python一些零零碎碎的东西太多了,在此记录一下。more文件操作
- 打开文件f = fopen(’test.txt’, ‘r’) 打开文件
f = fopen('test.txt', 'r')
f = fopen(’test.txt’, ‘r’)- 关闭文件f.close() 关闭文件
f.close()
f.close()- 按行读文件 按行读文件
for line in f.readlines():
data = line.strip()
for line in f.readlines(): data = line.strip()
- 读文件所有内容f.read() 读文件所有内容
f.read()
f.read()- 向文件写内容f.write(‘Hello World!\n’) 向文件写内容
f.write('Hello World!\n')
f.write(‘Hello World!\n’)- 获取目录下的文件列表files = glob.glob("./subcategory/*.html") 获取目录下的文件列表
files = glob.glob("./subcategory/*.html")
files = glob.glob("./subcategory/*.html")list, dict, set操作
- 二元组的list[(k1,v1),(k2,v2)]转为dict:dict = {k:v.data for k, v in blist} 二元组的list[(k1,v1),(k2,v2)]转为dict:
dict = {k:v.data for k, v in blist}
dict = {k:v.data for k, v in blist}- list添加元素: list添加元素:
b = [1]
b.append(2)
b = [1] b.append(2)
- set的使用 set的使用
s = Set([])
s.add(ele)
for i in s:
print i
s = Set([]) s.add(ele) for i in s: print iDom树操作
- 使用pyquery实现 使用pyquery实现
import PyQuery as pq
f = open(fname,'r')
c = f.read()
c = c.replace('gb2312','UTF-8'); #页面编码必须和指定编码一致。
d = pq(c) #d就与jquery中的$一样用了
sublist = d('#HidenDataArea').children()
for sub in sublist:
print d('a',sub).html()
import PyQuery as pq
f = open(fname,‘r’) c = f.read() c = c.replace(‘gb2312’,‘UTF-8’); #页面编码必须和指定编码一致。 d = pq(c) #d就与jquery中的$一样用了 sublist = d(’#HidenDataArea’).children() for sub in sublist: print d(‘a’,sub).html()sqlite的使用
import sqlite3 as lite
sqlite3.version
sqlite3.sqlite_version
con = None
try:
con = lite.connect('test.db')
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print "SQLite version: %s" % data
cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
except lite.Error, e:
print "Error %s:" % e.args[0]
sys.exit(1)
finally:
if con:
con.close()
import sqlite3 as lite sqlite3.version sqlite3.sqlite_version con = None
try: con = lite.connect(’test.db’)
cur = con.cursor()
cur.execute('SELECT SQLITE_VERSION()')
data = cur.fetchone()
print "SQLite version: %s" % data
cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
except lite.Error, e: print “Error %s:” % e.args[0] sys.exit(1) finally: if con: con.close() Categories: python