2012年5月10日 星期四

[Python Std Library] Built-in Types : File Objects


譯自 這裡
File Objects :
File objects are implemented using C’s stdio package and can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods, such as os.popen() and os.fdopen() and the makefile() method of socket objects. Temporary files can be created using the tempfile module, and high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

When a file operation fails for an I/O-related reason, the exception IOError is raised. This includes situations where the operation is not defined for some reason, like seek() on a tty device or writing a file opened for reading.

下面為 File object 提供的函數 :
- file.close()
關閉 file 物件. 被關閉後的 File 物件無法再進行讀寫動作, 如果嘗試對一個關閉的 File 物件讀寫會產生 ValueError 例外. 另外從 Python 2.5 你可以使用 with statement 在File 物件操作完畢後自動關閉該 File 物件. 底下為範例代碼 :
  1. from __future__ import with_statement # This isn't required in Python 2.6  
  2.   
  3. with open("hello.txt") as f:  
  4.     for line in f:  
  5.         print line  
在比較舊版本的代碼, 可能如下開啟/關閉 File 物件 :
  1. f = open("test.txt")  
  2.   
  3. try:  
  4.     for line in f:  
  5.         print("Line:{}".format(line.strip()))  
  6. finally:  
  7.     f.close()  

- file.flush()
Flush the internal buffer, like stdio‘s fflush(). This may be a no-op on some file-like objects.
Note flush() does not necessarily write the file’s data to disk. Use flush() followed by os.fsync() to ensure this behavior.

- file.next()
參考 Python Iterator Type, 因為這個方法, 你可以如下使用 for loop 一行行取出 File 物件的內容 :

- file.read([size])
從檔案讀取最多 size bytes 的內容. 如果 size 為負值或者沒有給, 則讀取全部內容.
>>> fh = open('test.txt')
>>> fh.read() # 讀取檔案所有內容.
'Hi John.\nThis is a test doc\nLine1\nLine2\nLine3\nEnd of line'
>>> fh.read(8) # 因為讀寫頭已經到 EOF, 故讀出為空字串.
''
>>> fh.seek(0) # 將讀寫頭返回 BOF (Begin of File)
0
>>> fh.read(8) # 讀取 8 bytes 內容.
'Hi John.'

- file.readline([size])
如果 size 沒給的話, 返回一行的內容 (含 '\n') ; 如果 size 為大於零的值, 則返回最多 size 的內容 (遇到換行, 則會停下來而讀取少於 size 的內容).

- file.readlines([sizehint])
如果 sizehint 沒給的話, 將檔案內容以行為單位, 返回串列 ; 如果 sizehint 有給的話, 返回最少包含 sizehint 大小的行數(不含 '\n'), 並以串列回傳.
>>> fh = open('test.txt')
>>> fh.readlines()
['Hi John.\n', 'This is a test doc\n', 'Line1\n', 'Line2\n', 'Line3\n', 'End of line']
>>> fh.seek(0)
>>> fh.readlines(8) # 讀取行數至少包含 8 bytes. 'Hi John.' 共 8 bytes, 故返回第一行.
['Hi John.\n']
>>> fh.seek(0)
>>> fh.readlines(9) # 因為第一行不夠 9 bytes, 故返回第一, 二行.
['Hi John.\n', 'This is a test doc\n']

- file.seek(offset[, whence])
將操作位置移到 offset 的地方 ; whence 為 offset 相對的點, 值可以是 os.SEEK_SET or 0 (預設), os.SEEK_CUR or 1 與 os.SEEK_END or 2.
>>> fh = open('test.txt')
>>> fh.read() # 讀取所有內容
'Hi John.\nThis is a test doc\nLine1\nLine2\nLine3\nEnd of line'
>>> fh.seek(3) # 將讀寫頭移到第 3 byte, 下一個從第 4 byte 讀起.
>>> fh.read(4)
'John'

- file.tell()
返回目前已操作的最後一個位置.
>>> fh = open('test.txt')
>>> fh.read(7) # 讀取 7 bytes
'Hi John'
>>> fh.tell()
7

- file.write(str)
寫入 str 的內容到檔案, 寫入不代表I/O 完成, 有可能會先在 buffer 中, 等到一定大寫才進行 IO 操作. 可以使用 flush() or close() 強迫 IO 操作.
>>> fh = open('test2.txt', 'w') # 使用 'w' 模式開啟檔案 'test2.txt'
>>> fh.write('Hi John\n')
8 # 共寫入 8 bytes
>>> fh.write('Second line')
11
>>> fh.close()
>>> fh = open('test2.txt')
>>> fh.read()
'Hi John\nSecond line'

- file.writelines(sequence)
sequence 為 Sequence Types, 這個方法將 sequence 的內容依序寫入檔案中.
>>> fh = open('test2.txt', 'w')
>>> fh.writelines(['line1\n', 'line2', 'line3\n', 'line4'])
>>> fh.close()
>>> fh = open('test2.txt')
>>> fh.read()
'line1\nline2line3\nline4'

以上為檔案物件提供的方法, 其實檔案物件上也有某些屬性值得你參考 :
- file.closed
此為唯獨屬性, 判斷檔案是否已經關閉. 當你呼叫 close() 會改變此屬性.
>>> fh = open('test2.txt')
>>> fh.closed
False
>>> fh.close()
>>> fh.closed
True

- file.mode
唯讀屬性, 為你使用 open() 打開檔案時的 I/O mode (如果沒有指定, 預設是 'r').
>>> fh = open('test2.txt')
>>> fh.mode
'r'
>>> fh.close()
>>> fh.mode
'r'
>>> fh = open('test2.txt', 'w')
>>> fh.mode
'w'

- file.name
唯讀屬性, 代表你使用 open() 打開的檔案名稱.
>>> fh = open('test2.txt', 'w')
>>> fh.name
'test2.txt'
This message was edited 25 times. Last update was at 20/03/2012 15:26:41

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...