讀取文件內(nèi)容
- 文件路徑的操作需要導(dǎo)入os模塊
- python中文件操作3個(gè)步驟:
- 調(diào)用open()函數(shù)柔昼,返回一個(gè)File對(duì)象。
- 調(diào)用File對(duì)象的讀寫方法。
- read()方法,將整個(gè)文件的內(nèi)容讀取為一個(gè)字符串值环疼。
- readlines()方法,從文件取得一個(gè)字符串的列表朵耕,列表中的每個(gè)字符串就是文本中的一行炫隶。注意:除了文件的最后一行,每個(gè)字符串值都以一個(gè)換行字符\n結(jié)束阎曹。
- 調(diào)用File對(duì)象的close()方法伪阶。
用shelve模塊保存變量
>>> import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie','Pooka','Simon']
>>> shelfFile['cats'] = cats
>>> shelFile.close()
在當(dāng)前目錄下出現(xiàn)三個(gè)新的文件:
mydata.bak
mydata.dat
mydata.dir
讀取shelve保持的變量:
>>> shelfFile = shelve.open('mydata')
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
>>> shelfFile.close()
shelf值也有鍵和值類似的列表值,但shelve變量的這些方法返回的不是真正的列表处嫌,所以要將他們傳遞給list()函數(shù)栅贴,取得列表的形式。
>>> shelfFile = shelve.open('mydata')
>>> list(shelfFile.keys())
['cats']
>>> list(shelfFile.values())
[['Zophie', 'Pooka', 'Simon']]
>>> shelfFile.close()
創(chuàng)建文件時(shí)熏迹,如果要在文本編輯器中讀取他們檐薯,純文本非常有用。如果想要保持python程序中的數(shù)據(jù)注暗,用shelve模塊更為明智坛缕。
用pprint.pformat()函數(shù)保持變量
如果想要將變量輸出到文本且,格式漂亮捆昏。那么可以導(dǎo)入pprint模塊來用赚楚。
- pprint.pprint()函數(shù)將列表或字典中的內(nèi)容“漂亮打印”到屏幕。
- pprint.pformat()函數(shù)將返回同樣格式的文本字符串屡立,但是不打印它直晨。
文件名可以用變量來控制編號(hào)如:
answerKeyFile = open('capitalsquiz_answer%s.txt' % (quizNum + 1), 'w')