讀取、寫入和 Python
編寫程序的最后一個基本步驟就是從文件讀取數據和把數據寫入文件。閱讀完這篇文章之后,可以在自己的 to-do 列表中加上檢驗這個技能學習效果的任務。
簡單輸出
貫穿整個系列,一直用 print 語句寫入(輸出)數據,它默認把表達式作為 string 寫到屏幕上(或控制臺窗口上)。清單 1 演示了這一點。清單 1 重復了第一個 Python 程序 “Hello, World!”,但是做了一些小的調整。
清單 1. 簡單輸出
>>> print "Hello World!"Hello World!>>> print "The total value is = $", 40.0*45.50The total value is = $ 1820.0>>> print "The total value = $%6.2f" % (40.0*45.50)The total value = $1820.00>>> myfile = file("testit.txt", 'w')>>> print >> myfile, "Hello World!">>> print >> myfile, "The total value = $%6.2f" % (40.0*45.50)>>> myfile.close()
正如這個示例演示的,用 print 語句寫入數據很容易。首先,示例輸出一個簡單的 string。然后創建并輸出復合的 string,這個字符串是用 string 格式化技術創建的。
但是,在這之后,事情發生了變化,與代碼以前的版本不同。接下來的一行創建 file 對象,傳遞進名稱 "testit.txt" 和 'w' 字符(寫入文件)。然后使用修改過的 print 語句 —— 兩個大于號后邊跟著容納 file 對象的變量 —— 寫入相同的 string。但是這一次,數據不是在屏幕上顯示。很自然的問題是:數據去哪兒了?而且,這個 file 對象是什么?
第一個問題很容易回答。請查找 testit.txt 文件,并像下面那樣顯示它的內容。
% more testit.txt Hello World!The total value = $1820.00
可以看到,數據被準確地寫入文件,就像以前寫到屏幕上一樣。
現在,請注意清單 1 中的最后一行,它調用 file 對象的 close 方法。在 Python 程序中這很重要,因為在默認情況下,文件輸入和輸出是緩沖的;在調用 print 語句時,數據實際未被寫入;相反,數據是成批寫入的。讓 Python 把數據寫入文件的最簡單方式就是顯式地調用 close 方法。
文件對象
file 是與計算機上的文件進行交互的基本機制。可以用 file 對象讀取數據、寫入數據或把數據添加到文件,以及處理二進制或文本數據。
學習 file 對象的最簡單方法就是閱讀幫助,如清單 2 所示。
清單 2. 得到 file 對象的幫助
>>> help(file)Help on class file in module __builtin__:class file(object) | file(name[, mode[, buffering]]) -> file object | | Open a file. The mode can be 'r', 'w' or 'a' for reading (default), | writing or appending. The file will be created if it doesn't exist | when opened for writing or appending; it will be truncated when | opened for writing. Add a 'b' to the mode for binary files. | Add a '+' to the mode to allow simultaneous reading and writing. | If the buffering argument is given, 0 means unbuffered, 1 means line | buffered, and larger numbers specify the buffer size. | Add a 'U' to mode to open the file for input with universal newline | support. Any line ending in the input file will be seen as a '/n' | in Python. Also, a file so opened gains the attribute 'newlines'; | the value for this attribute is one of None (no newline read yet), | '/r', '/n', '/r/n' or a tuple containing all the newline types seen. | | 'U' cannot be combined with 'w' or '+' mode. | | Note: open() is an alias for file(). | | Methods defined here:...
新聞熱點
疑難解答