Python3 输入和输出
输出格式美化、旧式格式化、键盘输入、文件读写、文件对象方法与 pickle。
输出格式美化
f-strings are the recommended way: prefix with f and put expressions inside braces, optionally followed by a format spec for width, precision, alignment or base. str.format() is the older equivalent.
name = "BackendWiki"
pi = 3.1415926
print(f"Hello, {name}!")
print(f"{pi:.2f}")
print(f"{name:>15}|")
print(f"{name:<15}|")
print(f"{name:^15}|")
print(f"{42:08b} {42:x} {42:o}")
print(f"{1234567:,}")
print(f"{0.256:.1%}")
print("Hello, {}! pi is {:.2f}".format(name, pi))
print("Hello, {n}! pi is {p:.2f}".format(n=name, p=pi))Hello, BackendWiki!
3.14
BackendWiki|
BackendWiki |
BackendWiki |
00101010 2a 52
1,234,567
25.6%
Hello, BackendWiki! pi is 3.14
Hello, BackendWiki! pi is 3.14旧式字符串格式化
Percent formatting follows C's printf: %s string, %d integer, %f float, %x hex. It survives in logging and legacy code; prefer f-strings for new code.
print("My name is %s and weight is %d kg!" % ('Zara', 21))
print("%.3f" % 3.1415926)
print("%5d|%-5d|" % (42, 42))
print("%x %o %e" % (255, 8, 1234.5678))
print("%(name)s is %(age)d" % {'name': 'Tom', 'age': 30})My name is Zara and weight is 21 kg!
3.142
42|42 |
ff 10 1.234568e+03
Tom is 30读取键盘输入
input() reads one line and returns it as a string without the trailing newline, optionally showing a prompt. It always returns a string — convert with int() / float() when you need numbers.
name = input("请输入你的名字:")
print("你好," + name)
# 需要数字时必须显式转换
age = int(input("请输入年龄:"))
print("明年你", age + 1, "岁")sys.stdin.readline() is more robust.读和写文件
open(name, mode, encoding=...) opens a file: r read, w truncate-write, a append, b binary. Always use with so the file closes on exit, even on exceptions.
with open('foo.txt', 'w', encoding='utf-8') as f:
f.write("Python 是一个非常好的语言。\n是的,的确非常好!!\n")
with open('foo.txt', 'r', encoding='utf-8') as f:
s = f.read()
print(repr(s))
print(len(s))'Python 是一个非常好的语言。\n是的,的确非常好!!\n'
29encoding='utf-8' in text mode. Otherwise the platform default applies (often GBK on Chinese Windows) and non-ASCII text breaks across machines.文件对象的方法
read(size) reads all or N characters, readline() one line, readlines() a list of lines; write() writes a string, writelines() a list of strings; seek(offset) moves the pointer and tell() reports it.
with open('foo.txt', 'w', encoding='utf-8', newline='') as f:
f.writelines(["line1\n", "line2\n", "line3\n"])
with open('foo.txt', 'r', encoding='utf-8', newline='') as f:
print(f.readline().strip())
print(f.tell())
f.seek(0)
print(len(f.readlines()))
with open('foo.txt', 'r', encoding='utf-8') as f:
for i, line in enumerate(f, 1):
print(i, line.strip())line1
6
3
1 line1
2 line2
3 line3pickle 模块
pickle serialises Python objects to bytes: dump/load work on file objects, dumps/loads on byte strings. Use it only between trusted parties — unpickling can execute arbitrary code.
import pickle
data = {'name': 'BackendWiki', 'tags': ['python', 'db'], 'n': 3}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
with open('data.pkl', 'rb') as f:
back = pickle.load(f)
print(back)
print(back == data)
blob = pickle.dumps([1, 2, 3])
print(len(blob) > 0, pickle.loads(blob)){'name': 'BackendWiki', 'tags': ['python', 'db'], 'n': 3}
True
True [1, 2, 3]pickle is version-bound and loading untrusted payloads equals running arbitrary code.格式化输出
print() separates arguments with a space and ends with a newline; override with sep and end. repr() gives the precise representation while str() is human-oriented — know which one you need when debugging.
print('a', 'b', 'c')
print('a', 'b', 'c', sep='-')
print('no newline', end='')
print(' -> continued')
s = 'hello\n'
print(str(s))
print(repr(s))
print(f"{'left':<8}|{'right':>8}|{'mid':^8}|")a b c
a-b-c
no newline -> continued
hello
'hello\n'
left | right| mid |输出格式美化
最推荐 f-string:在字符串前加 f,花括号内直接写表达式,还能跟格式说明符控制宽度、精度、对齐和进制。str.format() 是等价的旧写法。
name = "BackendWiki"
pi = 3.1415926
print(f"Hello, {name}!")
print(f"{pi:.2f}")
print(f"{name:>15}|")
print(f"{name:<15}|")
print(f"{name:^15}|")
print(f"{42:08b} {42:x} {42:o}")
print(f"{1234567:,}")
print(f"{0.256:.1%}")
print("Hello, {}! pi is {:.2f}".format(name, pi))
print("Hello, {n}! pi is {p:.2f}".format(n=name, p=pi))Hello, BackendWiki!
3.14
BackendWiki|
BackendWiki |
BackendWiki |
00101010 2a 52
1,234,567
25.6%
Hello, BackendWiki! pi is 3.14
Hello, BackendWiki! pi is 3.14旧式字符串格式化
百分号格式化沿用 C 的 printf 风格:%s 字符串、%d 整数、%f 浮点、%x 十六进制。它仍在日志与老代码里大量存在,新代码建议改用 f-string。
print("My name is %s and weight is %d kg!" % ('Zara', 21))
print("%.3f" % 3.1415926)
print("%5d|%-5d|" % (42, 42))
print("%x %o %e" % (255, 8, 1234.5678))
print("%(name)s is %(age)d" % {'name': 'Tom', 'age': 30})My name is Zara and weight is 21 kg!
3.142
42|42 |
ff 10 1.234568e+03
Tom is 30读取键盘输入
input() 读取一行输入并返回字符串(不含换行符),可以带提示语。它总是返回字符串,需要数字时要自己 int() / float() 转换。
name = input("请输入你的名字:")
print("你好," + name)
# 需要数字时必须显式转换
age = int(input("请输入年龄:"))
print("明年你", age + 1, "岁")sys.stdin.readline(),批量处理更稳妥。读和写文件
open(文件名, 模式, encoding=...) 打开文件,模式 r 读、w 覆盖写、a 追加、b 二进制。务必用 with 语句,退出时自动关闭文件,异常也不会漏关。
with open('foo.txt', 'w', encoding='utf-8') as f:
f.write("Python 是一个非常好的语言。\n是的,的确非常好!!\n")
with open('foo.txt', 'r', encoding='utf-8') as f:
s = f.read()
print(repr(s))
print(len(s))'Python 是一个非常好的语言。\n是的,的确非常好!!\n'
29encoding='utf-8'。不写会跟随系统默认编码(Windows 中文环境常是 GBK),跨平台读写中文极易乱码。文件对象的方法
read(size) 读全部或指定字节数、readline() 读一行、readlines() 读成行列表;write() 写字符串、writelines() 写字符串列表;seek(offset) 移动指针、tell() 返回当前位置。
with open('foo.txt', 'w', encoding='utf-8', newline='') as f:
f.writelines(["line1\n", "line2\n", "line3\n"])
with open('foo.txt', 'r', encoding='utf-8', newline='') as f:
print(f.readline().strip())
print(f.tell())
f.seek(0)
print(len(f.readlines()))
with open('foo.txt', 'r', encoding='utf-8') as f:
for i, line in enumerate(f, 1):
print(i, line.strip())line1
6
3
1 line1
2 line2
3 line3pickle 模块
pickle 把 Python 对象序列化成字节流存盘,dump/load 对应文件对象,dumps/loads 对应字节串。它只适合在可信环境中传递对象 —— 反序列化会执行任意代码。
import pickle
data = {'name': 'BackendWiki', 'tags': ['python', 'db'], 'n': 3}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
with open('data.pkl', 'rb') as f:
back = pickle.load(f)
print(back)
print(back == data)
blob = pickle.dumps([1, 2, 3])
print(len(blob) > 0, pickle.loads(blob)){'name': 'BackendWiki', 'tags': ['python', 'db'], 'n': 3}
True
True [1, 2, 3]pickle 的格式与 Python 版本绑定,且加载不可信数据等同于执行任意代码。格式化输出
print() 默认以空格分隔参数、结尾换行,可用 sep 和 end 改写;repr() 给出对象的准确表示,str() 给出面向人的表示,调试时两者要分清。
print('a', 'b', 'c')
print('a', 'b', 'c', sep='-')
print('no newline', end='')
print(' -> continued')
s = 'hello\n'
print(str(s))
print(repr(s))
print(f"{'left':<8}|{'right':>8}|{'mid':^8}|")a b c
a-b-c
no newline -> continued
hello
'hello\n'
left | right| mid |