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