簡介html
在以前的編程中,咱們的信息打印,數據的展現都是在控制檯(命令行)直接輸出的,信息都是一次性的沒有辦法複用和保存以便下次查看,今天咱們將學習Python的輸入輸出,解決以上問題。編程
複習app
獲得輸入用的是input(),完成輸出用的是print(),以前還有對字符串的操做,這些咱們均可以使用help()命令來查看具體的使用方法。函數
文件學習
在Python2的時候使用的是file來建立一個file類,對它進行操做。Python3中去掉了這個類(我沒有查到,只是猜想),使用open來打開一個文件,返回一個IO的文本包裝類,以後咱們使用這個類的方法對它進行操做。spa
使用文件命令行
poem = '''\ Programming is fun when the work is done if you wanna make your work also fun: use Python! ''' #poem1 = '''liu''' #讀模式('r')、寫模式('w')或追加模式('a')。 #若是有文件就讀取,沒有就建立 f = open('poem.txt','w') #f = open('poem.txt','a') f.write(poem) #f.write(poem1) f.close() type(f) print(f) f = open('poem.txt','r') while True: line = f.readline() if len(line) == 0: break print(line, end='') f.close()
運行結果code
如何工做htm
open方法第一個參數是你的文件名和路徑,個人文件和程序在同一個文件夾下因此只須要填寫文件名便可,第一個參數後面能夠跟不少參數來完成不一樣的操做,並且不少參數是由默認值的,經過咱們以前對函數的學習知道這樣作的好處。對象
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) ========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= ===============================================================
這個mode參數是主要的參數,你們記住這個就能夠,mode參數能夠不少個參連在一塊兒使用好比open('text1.txt','wb')這個就是使用二進制寫數據,一會就會使用到。
這個文件是不用手動建立的,在你的路徑下有這個文件的話,就會打開這個文件,若是沒有會自動建立這個文件。
讀文件的時候使用的是循環讀取,使用包裝類的readline()方法,讀取每一行,當方法返回0時,表示文件讀取完成,破壞循環條件,關閉IO。
自動建立的文件。
儲存器
import pickle as p shoplistfile = 'shoplist.data' shoplist = ['apple','mango','carrot'] f = open(shoplistfile,'wb') #將數據寫入打開的文件中 p.dump(shoplist,f) f.close() del shoplist f = open(shoplistfile,'rb') storedlist = p.load(f) print(storedlist) print(__doc__)
運行結果
這裏使用的就是二進制的寫入,讀取的時候也使用的二進制,和寫入的數據有關,這個你們多多留意。
Python的輸入與輸出就寫到這裏,你們多多探索會有更多的知識等待你發掘。
原文出處:https://www.cnblogs.com/liuhappy/p/10646871.html