首页 > 脚本语言 > python > 浅谈之 Python总结(整理)
2015
07-24

浅谈之 Python总结(整理)

一、简介

Python各方面的编程内容总结下来并不断更新,以便以后使用时查询。

二、详解

1、Python获取路径文件名

(1)split()函数进行字符串分割

浅谈之 Python总结(整理) - 第1张  | 大话运维

(2)basename()函数

浅谈之 Python总结(整理) - 第2张  | 大话运维

2、Python下的SQlite数据库

Python2.5集成了pysqlite数据库接口程序(sqlite3 模块),这是Python标准库第一次将一个数据库接口程序纳入标准库。
SQLite操作的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> import sqlite3
>>> cxn = sqlite3.connect('sqlite.db')
>>> cur = cxn.cursor()
>>> cur.execute('CREATE TABLE users(login VARCHAR(8), uid INTEGER)')
<sqlite3.Cursor object at 0x7f176e186710>
>>> cur.execute('INSERT INTO users VALUES("john", 100)')
<sqlite3.Cursor object at 0x7f176e186710>
>>> cur.execute('INSERT INTO users VALUES("jane", 110)')
<sqlite3.Cursor object at 0x7f176e186710>
>>> cur.execute('SELECT * FROM users')
<sqlite3.Cursor object at 0x7f176e186710>
>>> for eachUser in cur.fetchall():
...     print eachUser
...
(u'john', 100)
(u'jane', 110)
>>> cur.execute('DROP TABLE users')
<sqlite3.Cursor object at 0x7f176e186710>
>>> cur.close()
>>> cxn.commit()
>>> cxn.close()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env python
 
import os
from random import randrange as rrange
 
COLSIZ = 10
DB_EXC = None
 
def connect(dbDir, dbName):
global DB_EXC
try:
import sqlite3
except ImportError, e:
try:
from pysqlite2 import dbapi2 as sqlite3
except ImportError, e:
return None
 
DB_EXC = sqlite3
if not os.path.isdir(dbDir):
os.mkdir(dbDir)
cxn = sqlite3.connect(os.path.join(dbDir, dbName))
return cxn
 
def create(cur):
try:
cur.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')
except DB_EXC.OperationalError, e:
drop(cur)
create(cur)
 
drop = lambda cur: cur.execute('DROP TABLE users')
 
NAMES = (
('aaron', 8312), ('angela', 7603), ('dave', 7306),
('davina',7902), ('elliot', 7911), ('ernie', 7410),
('jess', 7912), ('jim', 7512), ('larry', 7311),
('leslie', 7808), ('melissa', 8602), ('pat', 7711),
('serena', 7003), ('stan', 7607), ('faye', 6812),
('amy', 7209),
)
 
def randName():
pick = list(NAMES)
while len(pick) > 0:
yield pick.pop(rrange(len(pick)))
 
def insert(cur):
cur.executemany("INSERT INTO users VALUES(?, ?, ?)",
[(who, uid, rrange(1,5)) for who, uid in randName()])
 
 
getRC = lambda cur: cur.rowcount if hasattr(cur, 'rowcount') else -1
 
def update(cur):
fr = rrange(1,5)
to = rrange(1,5)
cur.execute(
"UPDATE users SET prid=%d WHERE prid=%d" % (to, fr))
return fr, to, getRC(cur)
 
def delete(cur):
rm = rrange(1,5)
cur.execute('DELETE FROM users WHERE prid=%d' % rm)
return rm, getRC(cur)
 
def dbDump(cur):
cur.execute('SELECT * FROM users')
print '%s%s%s' % ('LOGIN'.ljust(COLSIZ),
'USERID'.ljust(COLSIZ), 'PROJ#'.ljust(COLSIZ))
for data in cur.fetchall():
print '%s%s%s' % tuple([str(s).title().ljust(COLSIZ) \
for s in data])
 
def main():
print '*** Connecting to sqlite database'
cxn = connect('sqlitedir', 'test.db')
if not cxn:
print 'ERROR: %r not supported, exiting' % db
return
cur = cxn.cursor()
 
print '*** Creating users table'
create(cur)
 
print '*** Inserting names into table'
insert(cur)
dbDump(cur)
 
print '*** Randomly moving folks',
fr, to, num = update(cur)
print 'from one group (%d) to another (%d)' % (fr, to)
print '\t(%d users moved)' % num
dbDump(cur)
 
print '*** Randomly choosing group',
rm, num = delete(cur)
print '(%d) to delete' % rm
print '\t(%d users removed)' % num
dbDump(cur)
 
print '*** Dropping users table'
drop(cur)
cur.close()
cxn.commit()
cxn.close()
 
if __name__ == '__main__':
main()
 
 

3、print函数输出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
>>> str = 'hello world'
>>> print str
hello world
>>> print 'length of (%s) is %d' %(str, len(str))
length of (hello world) is 11
>>> hex = 0xFF
>>> print 'hex = %x, dec = %d, oct=%o' % (hex, hex, hex)
hex = ff, dec = 255, oct=377
>>> import math
>>> print 'pi = %10.3f' % math.pi
pi =      3.142
>>> print 'pi = %-10.3f' % math.pi
pi = 3.142
>>> print 'pi = %06d' % int(math.pi)
pi = 000003
>>> precise = 4
>>> print ("%.*s" % (4,"python"))
pyth
>>> print ("%10.3s " % ("python"))
pyt
>>> lst = [1,2,3,4,'python']
>>> print lst
[1, 2, 3, 4, 'python']
>>> for i in range(0,6):
...     print i,
...
0 1 2 3 4 5
>>> import sys
>>> sys.stdout.write('hello world\n')
hello world

4、Python中文支持

添加一行声明文件编码的注释(python默认使用ASCII编码),必须将编码注释放在第一行或者第二行。

1
2
3
4
5
6
7
8
9
10
# -*- coding:utf-8 -*-
或者
 
#coding=utf-8
Windows下使用:
 
#coding=gbk
# -*- coding: gbk -*-
 
 
最后编辑:
作者:saunix
大型互联网公司linux系统运维攻城狮,专门担当消防员

留下一个回复