标签:http os 使用 文件 for 数据 ar line sp
Key Words: 文件迭代器,标准输入,GUI工具包,数据库操作SQLlite,
文件迭代器
>>> f= open("some.txt","r+")
>>> while True:
... line = f.readline()
... if not line : break
... else :
... print(line)
...
使用文件迭代器直接可以访问文件的每一行,而不必去使用readline方法。
>>> f= open("some.txt","r+")
>>> for line in f:
... print(line)
...
f.close()
标准输入sys. stdin:
from sys import *
for line in stdin:
if line == "bye":
break
else:
print(line)
支持Python的GUI工具包很多,使用wxPython做下面例子,wxPython是跨平台的,应用范围越来越广。
http://dev.mysql.com/downloads/connector/python/
使用Python自带的简单数据库SQLlite
>>> def format(value):
... if not value:
... return "0"
...
>>> import sqlite3
>>> conn = sqlite3.connect("food.db")
>>> curs = conn.cursor()
>>>
curs.execute执行具体的SQL语句。
>>> curs.execute(‘‘‘
... create table food(
... id text primary key,
... price float,
... amou float
... )
... ‘‘‘)
<sqlite3.Cursor object at 0x00BD34A0>
curs.execute(query,field)以匹配符的方式插入数据。
>>> query = "insert into food values(?,?,?)"
>>> for line in open("food.txt"):
... field = line.split(",")
... val = [format(f) for f in field]
... curs.execute(query,field)
...
<sqlite3.Cursor object at 0x00BD3860>
<sqlite3.Cursor object at 0x00BD3860>
<sqlite3.Cursor object at 0x00BD3860>
>>> curs.execute("select * from food")
<sqlite3.Cursor object at 0x00BD3860>
>>> conn.commit()
curs.fetchall()获取查询的结果。
>>> for row in curs.fetchall():
... print(row)
...
(‘apple‘, 3.0, 30.0)
(‘pear‘, 5.0, 20.0)
(‘banana‘, 3.0, ‘‘)
>>> conn.close()
sys.path下面有名为food.txt的文件,内容如下:
apple,3,30
pear,5,20
banana,3,
标签:http os 使用 文件 for 数据 ar line sp
原文地址:http://www.cnblogs.com/lnlvinso/p/3933740.html