亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

directory search
Python是什么? Python 3 教程 Python3 基礎(chǔ)語(yǔ)法 編碼 Python3 基本數(shù)據(jù)類型 Python解釋器 Python 注釋 Python 數(shù)字運(yùn)算 Python 字符串 Python 列表 Python 編程第一步 Python 條件控制 Python 循環(huán) Python 函數(shù) Python 數(shù)據(jù)結(jié)構(gòu) Python 模塊 Python 輸入和輸出 Python 錯(cuò)誤和異常 Python 類 Python 標(biāo)準(zhǔn)庫(kù)概覽 Python Hello World 實(shí)例 Python 數(shù)字求和 Python 平方根 Python 二次方程 Python 計(jì)算三角形的面積 Python 隨機(jī)數(shù)生成 Python 攝氏溫度轉(zhuǎn)華氏溫度 Python 交換變量 Python if 語(yǔ)句 Python 判斷字符串是否為數(shù)字 Python 判斷奇數(shù)偶數(shù) Python 判斷閏年 Python 獲取最大值函數(shù) Python 質(zhì)數(shù)判斷 Python 階乘實(shí)例 Python 九九乘法表 Python 斐波那契數(shù)列 Python 阿姆斯特朗數(shù) Python 十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制 Python ASCII碼與字符相互轉(zhuǎn)換 Python 最大公約數(shù)算法 Python 最小公倍數(shù)算法 Python 簡(jiǎn)單計(jì)算器實(shí)現(xiàn) Python 生成日歷 Python 使用遞歸斐波那契數(shù)列 Python 文件 IO Python 字符串判斷 Python 字符串大小寫轉(zhuǎn)換 Python 計(jì)算每個(gè)月天數(shù) Python 獲取昨天日期 Python list 常用操作 Python3 實(shí)例
characters

Python 輸入和輸出


在前面幾個(gè)章節(jié)中,我們其實(shí)已經(jīng)接觸了 Python 的輸入輸出的功能。本章節(jié)我們將具體介紹 Python 的輸入輸出。


輸出格式美化

Python兩種輸出值的方式: 表達(dá)式語(yǔ)句和 print() 函數(shù)。(第三種方式是使用文件對(duì)象的 write() 方法; 標(biāo)準(zhǔn)輸出文件可以用 sys.stdout 引用。)

如果你希望輸出的形式更加多樣,可以使用 str.format() 函數(shù)來(lái)格式化輸出值。

如果你希望將輸出的值轉(zhuǎn)成字符串,可以使用 repr() 或 str() 函數(shù)來(lái)實(shí)現(xiàn)。

str() 函數(shù)返回一個(gè)用戶易讀的表達(dá)形式。

repr() 產(chǎn)生一個(gè)解釋器易讀的表達(dá)形式。

例如

>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
>>> str(1/7)
'0.14285714285714285'
>>> 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...
>>> #  repr() 函數(shù)可以轉(zhuǎn)義字符串中的特殊字符
... hello = 'hello, world\n'
>>> hellos = repr(hello)
>>> print(hellos)
'hello, world\n'
>>> # repr() 的參數(shù)可以是 Python 的任何對(duì)象
... repr((x, y, ('spam', 'eggs')))
"(32.5, 40000, ('spam', 'eggs'))"

這里有兩種方式輸出一個(gè)平方與立方的表:

>>> for x in range(1, 11):
...     print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
...     # 注意前一行 'end' 的使用
...     print(repr(x*x*x).rjust(4))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

>>> for x in range(1, 11):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

注意:在第一個(gè)例子中, 每列間的空格由 print() 添加。

這個(gè)例子展示了字符串對(duì)象的 rjust() 方法, 它可以將字符串靠右, 并在左邊填充空格。

還有類似的方法, 如 ljust() 和 center()。 這些方法并不會(huì)寫任何東西, 它們僅僅返回新的字符串。

另一個(gè)方法 zfill(), 它會(huì)在數(shù)字的左邊填充 0,如下所示:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'

str.format() 的基本使用如下:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

括號(hào)及其里面的字符 (稱作格式化字段) 將會(huì)被 format() 中的參數(shù)替換。

在括號(hào)中的數(shù)字用于指向傳入對(duì)象在 format() 中的位置,如下所示:

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

如果在 format() 中使用了關(guān)鍵字參數(shù), 那么它們的值會(huì)指向使用該名字的參數(shù)。

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

位置及關(guān)鍵字參數(shù)可以任意的結(jié)合:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.
'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr()) 可以用于在格式化某個(gè)值之前對(duì)其進(jìn)行轉(zhuǎn)化:
>>> 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.

可選項(xiàng) ':' 和格式標(biāo)識(shí)符可以跟著字段名。 這就允許對(duì)值進(jìn)行更好的格式化。 下面的例子將 Pi 保留到小數(shù)點(diǎn)后三位:

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

在 ':' 后傳入一個(gè)整數(shù), 可以保證該域至少有這么多的寬度。 用于美化表格時(shí)很有用。

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
...     print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack       ==>       4098
Dcab       ==>       7678
Sjoerd     ==>       4127

如果你有一個(gè)很長(zhǎng)的格式化字符串, 而你不想將它們分開(kāi), 那么在格式化時(shí)通過(guò)變量名而非位置會(huì)是很好的事情。

最簡(jiǎn)單的就是傳入一個(gè)字典, 然后使用方括號(hào) '[]' 來(lái)訪問(wèn)鍵值 :

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
          'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

也可以通過(guò)在 table 變量前使用 '**' 來(lái)實(shí)現(xiàn)相同的功能:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

舊式字符串格式化

% 操作符也可以實(shí)現(xiàn)字符串格式化。 它將左邊的參數(shù)作為類似 sprintf() 式的格式化字符串, 而將右邊的代入, 然后返回格式化后的字符串. 例如:

>>> import math
>>> print('The value of PI is approximately %5.3f.' % math.pi)
The value of PI is approximately 3.142.

因?yàn)?str.format() 比較新的函數(shù), 大多數(shù)的 Python 代碼仍然使用 % 操作符。但是因?yàn)檫@種舊式的格式化最終會(huì)從該語(yǔ)言中移除, 應(yīng)該更多的使用 str.format().


讀和寫文件

open() 將會(huì)返回一個(gè) file 對(duì)象,基本語(yǔ)法格式如下:

open(filename, mode)

實(shí)例:

>>> f = open('/tmp/workfile', 'w')
  • 第一個(gè)參數(shù)為要打開(kāi)的文件名。
  • 第二個(gè)參數(shù)描述文件如何使用的字符。 mode 可以是 'r' 如果文件只讀, 'w' 只用于寫 (如果存在同名文件則將被刪除), 和 'a' 用于追加文件內(nèi)容; 所寫的任何數(shù)據(jù)都會(huì)被自動(dòng)增加到末尾. 'r+' 同時(shí)用于讀寫。 mode 參數(shù)是可選的; 'r' 將是默認(rèn)值。

文件對(duì)象的方法

本節(jié)中剩下的例子假設(shè)已經(jīng)創(chuàng)建了一個(gè)稱為 f 的文件對(duì)象。

f.read()

為了讀取一個(gè)文件的內(nèi)容,調(diào)用 f.read(size), 這將讀取一定數(shù)目的數(shù)據(jù), 然后作為字符串或字節(jié)對(duì)象返回。

size 是一個(gè)可選的數(shù)字類型的參數(shù)。 當(dāng) size 被忽略了或者為負(fù), 那么該文件的所有內(nèi)容都將被讀取并且返回。

>>> f.read()
'This is the entire file.\n'
>>> f.read()
''

f.readline()

f.readline() 會(huì)從文件中讀取單獨(dú)的一行。換行符為 '\n'。f.readline() 如果返回一個(gè)空字符串, 說(shuō)明已經(jīng)已經(jīng)讀取到最后一行。

>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''

f.readlines()

f.readlines() 將返回該文件中包含的所有行。

如果設(shè)置可選參數(shù) sizehint, 則讀取指定長(zhǎng)度的字節(jié), 并且將這些字節(jié)按行分割。

>>> f.readlines()
['This is the first line of the file.\n', 'Second line of the file\n']

另一種方式是迭代一個(gè)文件對(duì)象然后讀取每行:

>>> for line in f:
...     print(line, end='')
...
This is the first line of the file.
Second line of the file

這個(gè)方法很簡(jiǎn)單, 但是并沒(méi)有提供一個(gè)很好的控制。 因?yàn)閮烧叩奶幚頇C(jī)制不同, 最好不要混用。

f.write()

f.write(string) 將 string 寫入到文件中, 然后返回寫入的字符數(shù)。

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

如果要寫入一些不是字符串的東西, 那么將需要先進(jìn)行轉(zhuǎn)換:

>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
18

f.tell()

f.tell() 返回文件對(duì)象當(dāng)前所處的位置, 它是從文件開(kāi)頭開(kāi)始算起的字節(jié)數(shù)。

f.seek()

如果要改變文件當(dāng)前的位置, 可以使用 f.seek(offset, from_what) 函數(shù)。

from_what 的值, 如果是 0 表示開(kāi)頭, 如果是 1 表示當(dāng)前位置, 2 表示文件的結(jié)尾,例如:

  • seek(x,0) : 從起始位置即文件首行首字符開(kāi)始移動(dòng) x 個(gè)字符
  • seek(x,1) : 表示從當(dāng)前位置往后移動(dòng)x個(gè)字符
  • seek(-x,2):表示從文件的結(jié)尾往前移動(dòng)x個(gè)字符

from_what 值為默認(rèn)為0,即文件開(kāi)頭。下面給出一個(gè)完整的例子:

>>> f = open('/tmp/workfile', 'rb+')
>>> f.write(b'0123456789abcdef')
16
>>> f.seek(5)     # 移動(dòng)到文件的第六個(gè)字節(jié)
5
>>> f.read(1)
b'5'
>>> f.seek(-3, 2) # 移動(dòng)到文件的倒數(shù)第三字節(jié)
13
>>> f.read(1)
b'd'

f.close()

在文本文件中 (那些打開(kāi)文件的模式下沒(méi)有 b 的), 只會(huì)相對(duì)于文件起始位置進(jìn)行定位。

當(dāng)你處理完一個(gè)文件后, 調(diào)用 f.close() 來(lái)關(guān)閉文件并釋放系統(tǒng)的資源,如果嘗試再調(diào)用該文件,則會(huì)拋出異常。

>>> f.close()
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file
<pre>
<p>
當(dāng)處理一個(gè)文件對(duì)象時(shí), 使用 with 關(guān)鍵字是非常好的方式。在結(jié)束后, 它會(huì)幫你正確的關(guān)閉文件。 而且寫起來(lái)也比 try - finally 語(yǔ)句塊要簡(jiǎn)短:</p>
<pre>
>>> with open('/tmp/workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

文件對(duì)象還有其他方法, 如 isatty() 和 trucate(), 但這些通常比較少用。


pickle 模塊

python的pickle模塊實(shí)現(xiàn)了基本的數(shù)據(jù)序列和反序列化。

通過(guò)pickle模塊的序列化操作我們能夠?qū)⒊绦蛑羞\(yùn)行的對(duì)象信息保存到文件中去,永久存儲(chǔ)。

通過(guò)pickle模塊的反序列化操作,我們能夠從文件中創(chuàng)建上一次程序保存的對(duì)象。

基本接口:

pickle.dump(obj, file, [,protocol])

有了 pickle 這個(gè)對(duì)象, 就能對(duì) file 以讀取的形式打開(kāi):

x = pickle.load(file)

注解:從 file 中讀取一個(gè)字符串,并將它重構(gòu)為原來(lái)的python對(duì)象。

file: 類文件對(duì)象,有read()和readline()接口。

實(shí)例1:

#使用pickle模塊將數(shù)據(jù)對(duì)象保存到文件

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

實(shí)例2:

#使用pickle模塊從文件中重構(gòu)python對(duì)象

import pprint, pickle

pkl_file = open('data.pkl', 'rb')

data1 = pickle.load(pkl_file)
pprint.pprint(data1)

data2 = pickle.load(pkl_file)
pprint.pprint(data2)

pkl_file.close()
Previous article: Next article: