跳至內容

Python/輸入輸出

維基教科書,自由的教學讀本

鍵盤輸入

[編輯]

內置函數input()從標準輸入(sys.stdin)讀入一行文本,返回值要去掉回車符。拋出EOFError如果過早結束。

使用函數 eval() 把input()返回的值解釋執行。

文件

[編輯]

返回文件對象:

 open(filename, mode)

文件對象的方法:

  • close()
  • fileno()
  • flush()
  • isatty()
  • next()
  • read(size)
  • readline()
  • readlines() #也可以 for line in f:
  • seek()
  • tell()
  • truncate([size])
  • write(string)
  • writelines(sequence)

Python 3的read/write函數默認只接受string類型。二進制字節流,必須用'wb'這樣的模式打開文件。

pickle模塊實現了數據序列化和反序列化。方法為dump與load

Standard File Objects

[編輯]
import sys
for line in sys.stdin:
    print (line,)

sys.stdin.read()讀到EOF為止(通常為Ctrl+D)

分析命令行

[編輯]

sys.argv是一個列表,可修改。第一個元素是程序名本身(是否全路徑不一定)。

import sys
for arg in sys.argv[1:]:
  print (arg)

分析減號命名的命令行選項:

import sys
option_f = False
option_p = False
option_p_argument = ""
i = 1
while i < len(sys.argv):
  if sys.argv[i] == "-f":
    option_f = True
    sys.argv.pop(i)
  elif sys.argv[i] == "-p":
    option_p = True
    sys.argv.pop(i)
    option_p_argument = sys.argv.pop(i)
  else:
    i += 1

分析命令行還可以用包argparse (從Python 2.7) 與getopt (C程式設計師).

輸出

[編輯]

輸出值的方式:

  • print() 函數。
  • 文件對象的 write() 方法,標準輸出文件可以用 sys.stdout 引用。
  • str.format() 函數來格式化輸出值。
  • str(): 函數返回一個用戶易讀的表達形式。
  • repr(): 產生一個解釋器易讀的表達形式。

任何值都可以print。對於元組列印效果是在各項之間加一個空格來區隔:

print 1,2,0xff,0777,(10+5j),-0.999,map,sys

輸出為:

1 2 255 511 (10+5j) -0.999 <built-in function map> <module 'sys' (built-in)>


for i in range(10):
    print i,

輸出:

0 1 2 3 4 5 6 7 8 9

列印換行符的辦法是列印一個空行:

for i in range(10):
    print i,
print
for i in range(10,20):
    print i,

輸出

0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19

寫到文件:

print >> f, 'Hello, world'

任何實現了write()的對象都可以如上做。

忽略空格與換行符

[編輯]

為了避免在輸出結果中增加空格與換行符,有幾個辦法:

連接:

print str(1)+str(2)+str(0xff)+str(0777)+str(10+5j)+str(-0.999)+str(map)+str(sys)

輸出

12255511(10+5j)-0.999<built-in function map><module 'sys' (built-in)>

Write函數,即sys.stdout.write

import sys
write = sys.stdout.write
write('20')
write('05\n')

輸出

2005

用sys.stdout.flush()刷到屏幕

Python 3.x的示例:

  • from __future__ import print_function
    • Ensures Python 2.6 and later Python 2.x can use Python 3.x print function.
  • print ("Hello", "world")
    • Prints the two words separated with a space. Notice the surrounding brackets, ununsed in Python 2.x.
  • print ("Hello world", end="")
    • Prints without the ending newline.
  • print ("Hello", "world", sep="-")
    • Prints the two words separated with a dash.
  • print ("Error", file=sys.stderr)
    • Outputs to a file handle, in this case standard error stream.

文件輸出

[編輯]

用換行符分隔開:

file1 = open("TestFile.txt","w")
for i in range(1,10+1):
  print >>file1, i
file1.close()

使用減號分隔開,沒有換行符:

file1 = open("TestFile.txt","w")
for i in range(1,10+1):
  if i>1:
    file1.write("-")
  file1.write(str(i))
file1.close()

追加:

file1 = open("TestFile.txt","a")

格式化

[編輯]

格式化到字符串,使用「字符串百分號運算符」:

v1 = "Int: %i" % 4               # 4
v2 = "Int zero padded: %03i" % 4 # 004
v3 = "Int space padded: %3i" % 4 #   4
v4 = "Hex: %x" % 31              # 1f
v5 = "Hex 2: %X" % 31            # 1F - capitalized F
v6 = "Oct: %o" % 8               # 10
v7 = "Float: %f" % 2.4           # 2.400000
v8 = "Float: %.2f" % 2.4         # 2.40
v9 = "Float in exp: %e" % 2.4    # 2.400000e+00
vA = "Float in exp: %E" % 2.4    # 2.400000E+00
vB = "List as string: %s" % [1, 2, 3]
vC = "Left padded str: %10s" % "cat"
vD = "Right padded str: %-10s" % "cat"
vE = "Truncated str: %.2s" % "cat"
vF = "Dict value str: %(age)s" % {"age": 20}
vG = "Char: %c" % 65             # A
vH = "Char: %c" % "A"            # A

格式化到字符串,使用format()字符串方法,Python 2.6引入:

v1 = "Arg 0: {0}".format(31)     # 31
v2 = "Args 0 and 1: {0}, {1}".format(31, 65)
v3 = "Args 0 and 1: {}, {}".format(31, 65)
v4 = "Arg indexed: {0[0]}".format(["e1", "e2"])
v5 = "Arg named: {a}".format(a=31)
v6 = "Hex: {0:x}".format(31)     # 1f
v7 = "Hex: {:x}".format(31)      # 1f - arg 0 is implied
v8 = "Char: {0:c}".format(65)    # A
v9 = "Hex: {:{h}}".format(31, h="x") # 1f - nested evaluation

格式化到字符串,使用字面量字符串插值, Python 3.6引入:

int1 = 31; int2 = 41; str1="aaa"; myhex = "x"
v1 = f"Two ints: {int1} {int2}"
v2 = f"Int plus 1: {int1+1}"      # 32 - expression evaluation
v3 = f"Str len: {len(str1)}"      # 3 - expression evaluation
v4 = f"Hex: {int1:x}"             # 1f
v5 = f"Hex: {int1:{myhex}}"       # 1f - nested evaluation