Python 2.7基礎教學之:輸入輸出

黄舟
發布: 2016-12-24 17:12:50
原創
1810 人瀏覽過

.. _tut-io:

*************************************

Input and Output 輸入與輸出

*************************************

There are several ways to present the output of a program; data can be printed

in a human-readable form, or written to a file for future use. This chapter will

discuss some of the possibilities.

結果;資料可以列印為人類可讀的形式,也可以寫

入文件以供日後使用。本章將討論幾種可選的方法。

.. _tut-formatting:

Fancier Output Formatting 玩輸出格式

================================= ==============

So far we've encountered two ways of writing values: *expression statements* and

the :keyword:`print` statement.  (A third way is is using the :meth:`write` method

of file objects; the standard output file can be referenced as ``sys.stdout``.

See the Library Reference for more information on this.)

的輸出值方法: *表達式語句* 和:keyword:`print` 語句。 (第三種存取

是使用檔案物件的:meth:`write` 方法,標準檔案輸出可參考

``sys.stdout`` 。詳細內容請參閱資料庫參考手冊。) 

.. index:: module: string

Often you'll want more control over the formatting of your output than simply

printing space-separated values.  There are two ways to format your output; the

first way is to do all the string handling yourself ; using string slicing and

concatenation operations you can create any layout you can imagine.  The

standard module :mod:`string` contains some useful operations for mmm operations ortly. The second

way is to use the :meth:`str.format` method.

可能你經常想要對輸出格式做一些比簡單的打印空格分隔符更為複雜的控制。有

兩種方法可以格式化輸出。第一種是由你來控制整個字串,使用字元切割和聯

接操作就可以創造出任何你想要的輸出形式。標準模組 :mod:`string` 包括了一些操

作,將字串填充入給定列時,這些操作很有用。隨後我們會討論這部分內容。

第二種方法是使用 :meth:`str.format` 方法。

One question remains, of course: how do you convert values to strings? Luckily,

Python has ways to convert any value to a string: pass. ` functions.

當然,還有一個問題,如何將值轉換為字串?很幸運,Python 有辦法將任意

值轉為字串:將它傳入 :func:`repr` 或 :func:`str` 函數。

The :func:`str` function is meant to return representations of values which are

fairly human-readable, while :func:`repr` is meant to generate resperationsich unkations force a :exc:`SyntaxError` if

there is not equivalent syntax).  For objects which don't have a particular

🜥: human consumption, :functional : str. :`repr`.  Many values, such as numbers or structures like lists and

dictionaries, such as numbers or structures like lists and

dictionaries, have the same representation using either function.  Strings and

floop nidu. unc: `str` 用於將值轉換為適於人閱讀的形式,而:func:`repr` 轉換為供解釋器讀取

取的形式(如果沒有等價的語法,則會發生:exc:`SyntaxError ` 異常) 某個物件沒有適

於人閱讀的解釋形式的話, :func:`str` 會傳回與:func:`repr` 等同的值。很多類型,諸

如數值或鍊錶、字典這樣的結構,針對各函數都有統一的解讀方式。字串和

浮點數,有著獨特的解讀方式。

Some examples:

下面有一些例子::

   >>> s = 'Hello, world.'

   >>> str(s)

🎠

>> reprࠟ>. )

   "'Hello, world.'"

   >>> str(1.0/7.0)

   '0.142857142857'

. 14285714285'

   >>> x = 10 * 3.25

   >>> y = 200 * 200

   >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'

   >>> print s

   The value of x is 32.5, and y is 40000...

   >>> # The repr() of a string

   >>es: # The repr() of a string com

   ...你好='你好,世界/n'

  >>>>你好= repr(你好)

  >>>>>>印你好

   '你好,世界/n'

   >>>>> # repr() 的參數可以是任何Python 物件:

   ... repr((x, y, ('spam', 'eggs')))

   "(32 ('spam', '雞蛋'))"

這裡有兩種寫正方形和立方錶的方法:

有兩種方法可以寫平方和立方表::

   >>>> for x in range( 1, 11):

   ...     print repr(x).rjust(2), repr(x*x).rjust(3),

   ...     # 注意上一行的尾隨號 ...印刷repr(x*x*x).rjust(4)

   ...

   1   1    1

    2   4      4 16 64

   5  25  125

    6  36  216

    7  49  343

    8  64  512

    9  81  729

    9  81  729 對

,11):

   ...     print '{0:2d} {1:3d } {2:4d}'.format(x, x*x, x*x*x)

...

    1   1    1

   2   4    1

   2   4    1

      4  16   64

    5 25  125

    6  36  216

    7  49  343

 10 100 1000

(請注意,在第一個範例中,每列之間新增一個空格

方式:keyword:`print` 有效:它總是在其參數之間添加空格。

數字間添加空格。  還有類似的方法:meth:`ljust` 和:meth:`center`。  這些

方法不寫任何東西,它們只是回傳一個新字串。  如果輸入

字串太長,他們不會截斷它,而是原樣返回;這會

弄亂你的列佈局,但這通常比替代方案

更好,因為後者會謊報一個值。 (如果你真的想要截斷,你可以

始終添加切片操作,如``x.ljust(n)[:n]``中所示。)

以上是一個:meth:`rjust` 方法的演示,它把字串輸出到一列,並透過向左

側填充空格來設定右對齊。類似的方法還有 :meth:`ljust` 和 :meth:`center`

。這些函數只是輸出新的字串,並不是改變什麼。如果輸出的字串太長,它們也不會斷斷

它,而是原樣輸出,這使得你的輸出格式變得混亂,不過總強過另一種選擇(截斷)

斷字串),因為這樣會產生錯誤的輸出值。 (如果你確實需要截斷它,可以使

用切分操作,例如: ``x.ljust( n)[:n]`` 。)

還有另一種方法,:meth:`zfill` ,它用零填充左側的數字字串

。  它理解加號和減號:

還有另一個方法, :meth:`zfill` 它用於向數值的字串表達式箭頭填入 0。此

函數正確理解正負號::

>>>>> '12'.zfill(5)

   '00012'

   >> '

   >>> '3.14159265359'.zfill(5)

   '3.14159265359'

:meth:`str.format` 方法的基本使用方法的基本使用方式::

  >> print '我們是說「{}!」的{}'.format('knights', 'Ni')

   我們是說「Ni!」的騎士

其中的括號和字元(稱為格式欄位) ) 被替換為

傳遞到:meth:`~str.format` 方法中的物件。  

括號中的數字表示傳入

:meth:`~str.format`方法的物件的位置。 :

大表格和其中的字元會被替換成格式化 :meth:`~str.format` 的參數。大表格中

的數值指定使用格式化 :meth:`~str.format` 方法的物件中的哪一個::

   >>> print '{0} and {1}'.format('spam', 'eggs')

   spam and eggs

   >>> print '{1} and {0}'.format('spam ', 'eggs')

   eggs and spam

If keyword arguments are used in the :meth:`~str.format` method, their values

are referred to by using the name.在:meth:`~str.format` 呼叫時使用關鍵字參數,可以透過參數名稱來引用

值::

   >>> print 'This {food} is {adjective}.'.format(

....       food='spam', adjective='absolutely horrible')

   This spam is absolutely horrible.

Positional and keyword arguments can 的   > >> print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',

   ...                other='Georg'),

tory. The . Manfred, and Georg.

``'!s'`` (apply :func:`str`) and ``'!r'`` (apply :func:`repr`) can be used to

convert the value before it is formatted. :

``'!s'`` (應用:func:`str` ) 和``'!r'`` (應用:func:`repr` ) 可以

在格式化之前轉換值。 ::

   >>> import math

   >>> print 'The value of PI is approximately {}.'.format(math.pi)

   The value of PI is approximately 3.14159265359.

   >>> print ' The value of PI is approximately {!r}.'.format(math.pi)

   The value of PI is approximately 3.141592653589793.

optional `````有s s````l option ``s option ``s`` optional ``s options ``f option ``s``s option ``s`em optional ``s op. allows

greater control over how the value is formatted.  The following example

tru​​ncates Pi to three places after the decimal.

字段名後允許可選的``':'`` 和指令。這允許對值的格式化加以更深入的

控制。下例將 Pi 轉為三位精度。 ::

   >>> import math

   >>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)

   The value. an integer after the ``':'`` will cause that field to be a minimum

number of characters wide.  This is useful for making tables pretty. :

在字段後的` 上加一個整數會限定該欄位的最小寬度,這在美化表格時

很有用。 ::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}

   >>> for name, phone in table.items( '{0:10} ==> {1:10d}'.format(name, phone)

   ...

   Jack       ==>      

   Sjoerd     ==>       4127

If you have a really long format string that you don't want to split up, it

would be nice if you could reference the variables to be formatted by name

instead of by position. be formatted by name

instead of by position. be formatted by name

dict and using

square brackets ``'[]'`` to access the keys :

如果你有個實在是很長的格式化字符串,不想分割它。如果你可以用命名來引用

被格式化的變數而不是位置就好了。有個簡單的方法,可以傳入一個字典,用中

括號存取它的鍵::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

   >>> print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '

   ...        'Dcab: {0[Dcab]:d}'.format(d}'. table))

   Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This could also be done by passing the table as keyword arguments with the ''nopments;將這個字典以關鍵字參數的方式傳入。 ::

   >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}

   >>> print 'Jack: {Jack:d}; Sjoerd:d}; Sjoerd:d}; ; Dcab: {Dcab:d}'.format(**table)

   Jack: 4098; Sjoerd: 4127; Dcab: 8637678

This is particularly useful in combination the

This is particularly useful in combination the 假:new

function, which returns a dictionary containing all local variables.

這種方式與新的內建函數 :func:`vars` 組合使用非常有效。此函數傳回包含所有局

部變數的字典。

For a complete overview of string formatting with :meth:`str.format`, see

:ref:`formatstrings`.

要進一步了解字串格式化方法:meth:`str.format` ,請參閱

要進一步了解字串格式化方法:meth:`str.format` ,請參閱

要進一步了解字串格式化方法:meth:`str.format` ,參見

:ref:`formatstrings` 。

Old string formatting 舊式的字串格式化

------------------------------------- -----

The ``%`` operator can also be used for string formatting. It interprets the

left argument much like a :cfunc:`sprintf`/ -style format string to be applied the be app right argument, and returns the string resulting from this formatting

operation. For example:

運算符``%`` 也可以用於字串格式化。它以類似:cfunc:`sprintf` 的方式

解析左參數,將右參數套用於此,得到格式化操作產生的字串,例如::

   >>> import math

   >>> print ' The value of PI is approximately %5.3f.' % math.pi

   The value of PI is approximately 3.142.

Since :meth:`str.format` is quite new a. %``

operator. However, because this old style of formatting will eventually be

removed from the language, :meth:`str.format` should generally be used.

很新,大量Python 程式碼還在使用``%`` 操作符。

然而,因為舊式的格式化方法最終將從語言中去掉,應該盡量使用

 :meth:`str.format` 。

More information can be found in the :ref:`string-formatting` section.

進一步的資訊可以參見 :ref:`string-formatting` 一節。

.. _tut-files:

Reading and Writing Files 讀寫檔案

=============================== ===============

.. index::

   builtin: open

   object: file

:func:`open` returns a object: file

:funcused 1.com with two

arguments: ``open(filename, mode)``.

函數:func:`open` 傳回檔案對象,通常的用法需要兩個參數:

``open(filename, mode)`` 。

::

   >>> f = open('/tmp/workfile', 'w')

   >>> print f

  

The first argument is a string containing the filename.  The second argument is a string containing the filename.  The second argument is a string containing the filename.  The second argument is a string containing the filename。 the file will only be read, ``'w'``

for only writing (an existing file with the same name will be erased), and

``'a'`` opens the file for appending; any written to the file is

automatically added to the end.  ``'r+'`` opens the file for both reading and

writing. The *mode* argument is optional; ``'r'` will it's

omitted.

第一個參數是一個標識檔案名稱的字串。第二個參數是由有限的字母組成的字元

串,描述了檔案將會被如何使用。可選的*模式* 有: ``'r'`` ,此選項使文件只讀;

``'w'`` ,此選項使文件只寫(對於同名文件,該操作使原有文件被覆寫); ``'a'`` ,

此選項以追加方式開啟檔案; ``'r+'`` ,此選項以讀寫方式開啟檔案; 

*模式* 參數是可選的。如果沒有指定,預設為 ``'r'`` 模式。

On Windows, ``'b'`` appended to the mode opens the file in binary mode, so there

are also modes like ``'rb'``, ``'wb'``, and `` 'r+b'``.  Python on Windows makes

a distinction between text and binary files; the end-of-line characters in text

files are automatically altered sodacters in text

file the-scenes modification to file data is fine for ASCII text files, but

it'll corrupt binary data like that in :file:`JPEG` or :file:`EXE` files。 when reading and writing such files.  On Unix,

it doesn't hurt to append a ``'b'`` to the mode, so you can use it

ary

platform-independently for all bin files.在平台上, ``'b'`` 模式以二進位方式開啟文件,所以可能會

有類似``'rb'`` , ``'wb'`` , ``'r+b'``等等模式組合。 Windows 平台上文字檔案與二

進位檔案是有區別的,讀寫文字檔案時,行尾會自動新增行結束符號。這種後台操

作方式對 ASCII 文字檔案沒有什麼問題,但是操作 JPEG 或 .EXE這樣的二進位

檔案時就會產生破壞。在操作這些檔案時一定要記得以二進位模式開啟。在

Unix 上,加上一個 ``'b'`` 模式也一樣是無害的,所以你可以一切二進位檔案處

理中平台無關的使用它。

.. _tut-filemethods:

Methods of File Objects 檔案物件方法

------------------------------- ----------

The rest of the examples in this section will assume that a file object called

``f`` has already been created.

本節中的範例都預設文件物件``f`` 已經創建。

To read a file's contents, call ``f.read(size)``, which reads some quantity of

data and returns it as a string.  *size* is an optional sizeiarahar*size* is an optional s*ar)* is omitted or negative, the entire contents of the file will be read and

returned; it's your problem if the file is twice as large as your machine's

mturn at terwiseed* Loc​​kyed* )l. the end of

the file has been reached, ``f.read()`` will return an empty string (``""``).

要讀取檔案內容,需要呼叫``f.read( size)`` ,此方法讀取若干數量的資料並以字

符串形式傳回其內容, *size* 是可選的數值,指定字串長度。如果沒有指定

size或指定為負數,就會讀取並傳回整個檔案。當檔案大小為目前機器記憶體兩

倍時,就會產生問題。反之,會盡可能按比較大的 size 讀取和回傳資料。

如果到了檔案末尾,f.read()會傳回一個空字串("")。

::

   >>> f.read()

   'This is the entire file./n'

   >>> f.read()

 ``(. ` reads a single line from the file; a newline character (``/n``)

is left at the end of the string, and is only omitted on the last line of the

fileif the filedon if' end in a newline.  This makes the return value

unambiguous; if ``f.readline()`` returns an empty string, the end of the file

has been reached, while a repached, while `resent by ``is 0ed. /n'``, a string

containing only a single newline. 

``f.readline()`` 從檔案中讀取單獨一行,字串結尾會自動加上一個換行符

( `` /n`` ),只有當檔案最後一行沒有以換行符號結尾時,這一操作才會被忽略。

這樣回傳值就不會有混淆,如果如果``f.readline()`` 回傳一個空字串,那就表

示到達了檔案末尾,如果是一個空行,就會描述為` `'/n`` ,一個只包含換行符的字串。 ::

   >>> f.readline()

   'This is the first line of the file./n'

   >>> f.readline()

   >>> f.readline()

 >>> f.readline()

   ''

``f.readlines()`` returns a list containing all the lines of data in the file.

If given an optional parameter *size

If given an optional parameter *sizes thathints many bytes from the

file and enough more to complete a line, and returns the lines from that.  This

is often used to allow efficient reading of a large fileby lines, out outjis, outcom memory.  Only complete lines will be returned.

f.readlines()傳回一個列表,其中包含了檔案中所有的資料行。如果給定了

*sizehint* 參數,就會讀入多於一行的比特數,從中傳回多行文字。這個功能

通常用於高效讀取大型行文件,避免了將整個文件讀入記憶體。這種操作只會回傳完

整的行。 ::

   >>> f.readlines()

   ['This is the first line of the file./n', 'Second line of the file/n']

An alternative approach to reading lineroach over the file object. This is

memory efficient, fast, and leads to simpler code

有個按行讀取的好方法是在檔案物件上循環。如此容易記憶,高速且程式碼更簡單::

   >>> for line in f:

           print line,

   This is the first line of the file.tern cop the file. is simpler but does not provide as fine-grained

control.  Since the two approaches manage line buffering differently, they

should not be mixed.

因為兩個方法用不同的方式管理行緩

沖區,它們不能混用。

``f.write(string)`` 將 *string* 的內容寫入文件,傳回

``None``。  

``f.write(string)`` 將 *string* 的內容寫入文件,回傳 ``None`` 。 ::

   >>>>> f.write('This is a test/n')

要寫入字串以外的東西,需要轉換為字串

first:

如果需要寫入字串以外的數據,先需要把這些數據轉換為字串。 ::

   >>> value = ('答案', 42)

   >>>>> s = str(值)

  >>>>> f.write(s)

`f.tell(`f.tell(`f.tell(`. )`` 傳回一個整數,給出檔案物件在

檔案中的目前位置,從檔案開頭開始以位元組為單位測量。  要更改檔案

物件的位置,請使用``f.seek(offset, from_what)``。  位置是透過將 *offset* 新增到參考點來計算的;參考點由

*from_what* 參數選擇。  *from_what* 值 0 從檔案的開頭

開始測量,1 使用目前檔案位置,2 使用檔案的結尾作為

參考點。  *from_what* 可以省略,預設為 0,使用

檔案的開頭作為參考點。 

``f.tell()`` 傳回一個整數,代表檔案物件在檔案中的指標位置,該數值計量了自文

件到指針處的位元數。需要改變文件物件指標話話,使用

``f.seek(offset,from_what)`` 。指標在該操作中從指定的引用位置移動 *offset*

位,引用位置由 *from_what* 參數指定。 *from_what* 值為 0 表示自檔案

開始處開始,1 表示自目前檔案指標位置開始,2 表示自檔案補充開始。 *from_what* 可以

忽略,預設其值為零,此時從檔案頭開始。 ::

>>>>> f = open('/tmp/workfile', 'r+')

   >>>>> f.write('0123456789abcdef')

eek  >>>>> 5)     # 前往檔案中的第6 個位元組

   >>>> f.read(1)

   '5'

   >>> f.seek(-3, 2) # 前往結束前的第3 個位元組

   >>>>> f.read(1)

   'd'

當您完成一個檔案時,呼叫``f.close()`` 來關閉它並釋放開啟檔案佔用的任何

系統資源。  呼叫``f.close()``後,

嘗試使用檔案物件將自動失敗。 

檔案使用完畢後,呼叫 ``f.close()`` 可以關閉文件,釋放開啟檔案後所佔用的系統資源。

呼叫 ``f.close()`` 之後,再呼叫檔案物件會自動引發錯誤。 ::

   >>>>> f.close()

   >>>>> f.read()

   回溯(最後一次調用最後一次):

     回溯(最近一次調用最後一次):

  ?

   ValueError: I/O 對關閉檔案的操作

使用:keyword:`with` 關鍵字處理檔案

物件時。  這樣做的優點是,即使在途中引發異常,文件也會在其

套件完成後正確關閉。  它也比寫等效的 :keyword:`try`/ -/ :keyword:`finally` 區塊

關鍵字用 :keyword:`with` 處理檔案物件短得多。它的先進之處相當於文件

用完後會自動關閉,就算發生異常也沒關係。是:keyword:`try`/ -/

:keyword:`finally`區塊的簡寫。 ::

    >>> with open('/tmp/workfile', 'r') as f:

    ...     read_data = f.read()

🠎物件還有一些額外的方法,例如:meth:`~file.isatty` 和

:meth:`~file.truncate` 這些方法較不常用;請查閱圖書館

參考文件物件的完整指南。

文件物件還有一些不太常用的附加方法,例如 :meth:`~file.isatty` 和 :meth:`~file.truncate` 在庫參

考手冊包含文件對象的完整指南。

.. _tut-pickle:

:mod:`pickle` 模組  :mod:`pickle` 模組

------------ ------------ --------------------------

.. 索引:: 模組:pickle

可以輕鬆地將字串寫入檔案或從文件中讀取字串。數字需要更多的努力

,因為:meth:`read` 方法只回傳字串,必須

將其傳遞給像:func:`int` 這樣的函數,該函數接受像``'123 這樣的字串'``

並傳回其數值123。但是,當你想保存更複雜的

data types like lists, dictionaries, or class instances, things get a lot more

complicated.

我們可以很容易的讀寫檔案中的字串。數值就要多費點兒周折,因為:meth:`read`

方法只會傳回字串,應該將其傳入:func:`int` 這樣的方法中,就可以將

``'123 '`` 這樣的字元轉為對應的數值123 。不過,當你需要保存更為複雜的

資料類型,例如列表、字典,類別的實例,事情就會變得更複雜了。

Rather than have users be constantly writing and debugging code to save

complicated data types, Python provides a standard module called :mod:`pickle`.evena​​h ​​語🜎

forms of Python code!), and convert it to a string representation; this process

is called :dfn:`pickling`.  Reconstructing the object from the string

木representation 句卷 cem. and unpickling,

the string representing the object may have been stored in a file or data, or

sent over a network connection to some distant machine.

代碼。 Python提供了

一個名為 :mod:`pickle` 的標準模組。這是一個令人讚嘆的模組,幾乎可以把任何

Python 物件 (甚至是一些 Python 程式碼片段!)表達為為字串,這一過程稱之

為封裝 ( :dfn:`pickling` )。從字串表達出重新建構物件稱為拆封

( :dfn:`unpickling` )。封裝狀態中的物件可以儲存在檔案或物件中,也可以透過網路

絡在遠端的機器之間傳輸。

If you have an object ``x``, and a file object ``f`` that's been opened for

writing, the simplest way to pickle the object kes

writing, the simplest way to pickle the object kes

writing, the simplest way to pickle the object kes only one takes ``x`` ,一個以寫入模式開啟的檔案物件``f`` ,封裝物件的最簡單的

方法只需要一行程式碼::

   pickle.dump(x, f)

To unpickle the object again, if ``f`` is a file object which has been opened

for reading

如果``f`` 是一個以讀取模式打開的文件對象,就可以重裝封這個對象::

   x = pickle.load(f)

(There are other variants of this, used when pickling many objects or when you

don't want to write the picklekled 數據 for

don't want to wple the picklekled datault: doctcom mod:`pickle` in the Python Library Reference.)

(如果不想把封裝的資料寫入文件,這裡還有一些其它的變化可用。完整的

:mod:`pickle` 文件請見Python 庫參考手冊)。

:mod:`pickle` is the standard way to make Python objects which can be stored and

reused by other programs or by a future invocation of the same program the

: for thenmmm ; persistent` object。 pickle` 是儲存Python 物件以供其它程式或其本身日後呼叫的標準方法。提供

這一組技術的是一個 :dfn:`持久化` 物件( :dfn:`persistent` object )。因為 :mod:`pickle` 的用

途很廣泛,許多 Python 擴充的作者都非常注意類似矩陣這樣的新資料型別是否適合封裝和拆封。

 以上就是Python 2.7基礎教學之:輸入輸出的內容,更多相關內容請關注PHP中文網(m.sbmmt.com)!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!