1. 程式人生 > >Android程式猿帶你學python第5章--輸入與輸出(I/O)

Android程式猿帶你學python第5章--輸入與輸出(I/O)

導讀


在第0章就說過,程式無非就是輸入->邏輯->輸出。所以如何處理輸入和輸出就顯得非常重要,常見的輸入有控制檯輸入,函式接受引數輸入,常見的輸出有控制檯輸出,檔案,資料庫等

常見的I/O處理


控制檯輸入輸出

>>print("hello")
>>s = input("please scan")
>>print(s)
這個之前已經用過很多次了


資料持久化

1.檔案

開啟檔案

>>f = open("xxx.txt)
#讀取檔案
>>for line in f:
    >>print(line) 

開啟模式
w:寫方式開啟檔案,如果檔案存在,清空
r:讀方式開啟檔案
a:追加的方式開啟檔案,如果檔案存在,指標自動到檔案尾部
a+:a+讀
w+:w+讀
b:以二進位制開啟檔案

寫檔案
f.write(“hello”) //追加還是重寫決定於開啟的模式和指標的位置
read()
readline()
readlines()
seek()移動
tell()指標目前的位置

pickle/cpickle

pickle提供了一個簡單的持久化功能。可以將物件以檔案的形式存放在磁碟上
//存
prickle.dump(object, file[protocol])
object:序列化物件
file:要寫入的檔案
protocol:可選項,預設為false,以ASCII格式儲存,如果設定為1或true,則以二進位制的形式儲存
//取
pickle.load(file)

舉個例子
#! /usr/bin/env python
#coding=utf-8

import pickle

l = ["tony","python", 2017, 6]
f = open("D:\\test.txt", "wb+") 
s = pickle.dump(l, f)
#必須先關閉,否則pickle.load(f1)會出現EOFError: Ran out of input  
f.close()
f = open("D:\\test.txt", "rb") 
ll = pickle.load(f)
print(ll)

ll的輸出結果:
["tony","python", 2017
, 6] 檔案裡的內容: €]q (X tonyqX pythonqM?Ke.


shelve

寫入

>>s = shelve.open("file")
>>s["name"] = "tony"
>>s["sex"] = "male"
>>s.close()


讀取

>>s = shelve.open("file")
>>name = s["name]
>>sex = s["sex"]


迴圈讀取

>>for k in s  :
    >>print(k + s[k])

修改已有鍵的值

>>s = shelve.open("file", writeback=true)
>>s["name"].append("tony2")


2.資料庫–關係型資料庫 mysql

下載mysql
連線驅動
PyMySQL https://pypi.python.org/pypi/PyMySQL#downloads

獲得資料庫連線物件
conn = pymysql.connect(host=’localhost’, port=3306, user=’root’, passwd=’w19920309z’, db=’test_db’,charset=’UTF8’)

獲得遊標
cur = conn.cursor()

self.cur.executemany("insert into users (username, password, email) values (%s,%s,%s)", (("python","123456","python@163c.om"), ("github", "1221", "tony@163.com")))
self.conn.commit()


#還記得之前講過的string的格式化嗎 3種方式
self.execute("update user set username=%s where id=2", ("mypython"))
self.conn.commit()


self.cur.execute("select * from users")
lines = self.cur.fetchall()
for line in lines:
    print(line)
self.cur.scroll(1, "absolute")
lines = self.cur.fetchall()
for line in lines:
    print(line)

總結


I/O在實際專案中使用頻率非常高,print()常用於一些簡單除錯,可以在控制檯看到流程走到哪了,輸出結果是否與期望保持一致
資料庫和檔案在Web專案裡被使用到,用於資料的持久化
在學完下一章異常處理,整個python的語法就全部結束了,可以找一些實際專案練練手,比如搭建一個網站