python讀取文本數據

總結
(1)推薦使用 with 語句操作文件 IO。
(2)如果文件較大,可以按字節讀取或按行讀取。
(3)使用文件迭代器進行逐行迭代。

1. python讀取文本文件實現機制
讀寫文件是最常見的IO操作。Python內置了讀寫文件的函數.
讀寫文件前,我們先必須瞭解一下,在磁盤上讀寫文件的功能都是由操作系統提供的,現代操作系統不允許普通的程序直接操作磁盤,所以,讀寫文件就是請求操作系統打開一個文件對象(通常稱爲文件描述符),然後,通過操作系統提供的接口從這個文件對象中讀取數據(讀文件),或者把數據寫入這個文件對象(寫文件)。

步驟 操作
第一步 請求操作系統打開一個文件對象
第二步 通過文件對象接口讀(寫)數據
第三步 關閉文件對象

2. python讀取文本文件之Python內置函數
(2.1.1).open()函數讀取文本文件demo:

完整過程:
f = open('/Users/michael/test.txt', 'r') # 請求操作系統打開一個文件對象 
f.read()  #通過文件對象接口讀(寫)數據
f.close() #關閉文件對象
其中:
1)第一步,標示符'r'表示讀,這樣,我們就成功地打開了一個文件。如果文件不存在,open()函數就會拋出一個IOError的錯誤,並且給出錯誤碼和詳細的信息告訴你文件不存在;
2)第二步,如果文件打開成功,接下來,調用read()方法可以一次讀取文件的全部內容,Python把內容讀到內存,用一個str對象表示;
3)第三步,是調用close()方法關閉文件。文件使用完畢後必須關閉,因爲文件對象會佔用操作系統的資源,並且操作系統同一時間能打開的文件數量也是有限的;
 ///////////////////////////////////////////////////////////////////
 從上可以看出,一旦上述過程忘記寫f.close()或者第二步讀寫文件出錯,文件打開後就不能被關閉,會佔用內存資源,因此,爲了保證無論是否出錯都能正確地關閉文件,我們可以使用try ... finally來實現:
try:
    f = open('/path/to/file', 'r')
    print f.read()
finally:
    if f:
        f.close()
上述寫法比較繁瑣,更優化的寫法,是用with實現,with實現方式跟try...finally...是一樣的,寫起來更方便;
with open('/path/to/file', 'r') as f:
    print f.read()
 ////////////////////////////////////////////////////
 讀取文件的方式:
 (1)一次性讀取文件的全部內容。f.read() 或者f.read(size)
 調用read()會一次性讀取文件的全部內容,如果文件有10G,內存就爆了,所以,要保險起見,可以反覆調用read(size)方法,每次最多讀取size個字節的內容。另外,調用readline()可以每次讀取一行內容,調用readlines()一次讀取所有內容並按行返回list。因此,要根據需要決定怎麼調用。如果文件很小,read()一次性讀取最方便;如果不能確定文件大小,反覆調用read(size)比較保險;如果是配置文件,調用readlines()最方便;
 (2)文件爲可迭代對象。for line in f.readlines():
    print(line.strip()) # 把末尾的'\n'刪掉

(2.1.2).open()函數寫文本文件:
寫文件和讀文件是一樣的,唯一區別是調用open()函數時,傳入標識符’w’或者’wb’表示寫文本文件或寫二進制文件;
open()函數寫文本文件demo:

原始方式:
>>> f = open('/Users/michael/test.txt', 'w')
>>> f.write('Hello, world!')
>>> f.close()
優化方式:
with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')
 ///////////////////////////////////////////
寫文件案例2:
with open('/Users/ethan/data2.txt', 'w') as f:
    f.write('one\n')
    f.write('two')
 註解:
(1)如果上述文件已存在,則會清空原內容並覆蓋掉;
(2)如果上述路徑是正確的(比如存在 /Users/ethan 的路徑),但是文件不存在(data2.txt 不存在),則會新建一個文件,並寫入上述內容;
(3)如果上述路徑是不正確的(比如將路徑寫成 /Users/eth ),這時會拋出 IOError;

with open('/home/ccs/tmp.txt', 'r') as f:
    lines = list(f) #將f字符串對象執行普通迭代器的操作,返回可迭代對象列表
    print(lines)

with open('/home/ccs/tmp.txt', 'r') as f:
    while True:
        line = f.readlines()     # readlines()函數返回整體爲可迭代對象列表
        if not line:
            break
        print(line)
'''
上面兩種讀文件方式結果:
['10  1   9   9\n', '6   3   2   8\n', '20  10  3   23\n', '1   4   1   10\n', '10  8   6   3\n', '10  2   1   6\n']
結論:
可以看到,我們可以對文件迭代器執行和普通迭代器相同的操作,比如上面使用 list(open(filename)) 將 f 轉爲一個字符串列表,這樣所達到的效果和使用 readlines 是一樣的。

'''

with open('/home/ccs/tmp.txt', 'r') as f:
    for line in f:
        print(line)

with open('/home/ccs/tmp.txt', 'r') as f:
    while True:
        line = f.readline()     # 逐行讀取
        if not line:
            break
        print(line)             # 這裏加了 ',' 是爲了避免 print 自動換行

'''
上面兩種讀文件方式結果:
10  1   9   9

6   3   2   8

20  10  3   23

1   4   1   10

10  8   6   3

10  2   1   6

結論:
使用open函數打開得到的文件對象本身f是可迭代的,利用普通for循環遍歷迭代取出元素值與f.readline迭代讀取每行元素值是一樣的;
'''

(2.1.3).open()函數工具:
def open(file, mode=‘r’, buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
“”"
Open file and return a stream. Raise IOError upon failure.

file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)

mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode.  Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:

========= ===============================================================
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)
========= ===============================================================

The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.

Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.

'U' mode is deprecated and will raise an exception in future versions
of Python.  It has no effect in Python 3.  Use newline to control
universal newlines mode.

buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer.  When no buffering argument is
given, the default buffering policy works as follows:

* Binary files are buffered in fixed-size chunks; the size of the buffer
  is chosen using a heuristic trying to determine the underlying device's
  "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
  On many systems, the buffer will typically be 4096 or 8192 bytes long.

* "Interactive" text files (files for which isatty() returns True)
  use line buffering.  Other text files use the policy described above
  for binary files.

encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed.  See the codecs module for the list of supported encodings.

errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.

newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
follows:

* On input, if newline is None, universal newlines mode is
  enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  these are translated into '\n' before being returned to the
  caller. If it is '', universal newline mode is enabled, but line
  endings are returned to the caller untranslated. If it has any of
  the other legal values, input lines are only terminated by the given
  string, and the line ending is returned to the caller untranslated.

* On output, if newline is None, any '\n' characters written are
  translated to the system default line separator, os.linesep. If
  newline is '' or '\n', no translation takes place. If newline is any
  of the other legal values, any '\n' characters written are translated
  to the given string.

If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.

A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).

open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.

It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章