Python3 输入和输出

输出格式美化、旧式格式化、键盘输入、文件读写、文件对象方法与 pickle。

Beginner
Key Points格式化首选 f-string;open 用 with 保证关闭,文本模式注意 encoding='utf-8';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.

Python
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))
Output
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.

Python
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})
Output
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.

Python
name = input("请输入你的名字:")
print("你好," + name)

# 需要数字时必须显式转换
age = int(input("请输入年龄:"))
print("明年你", age + 1, "岁")
The example above waits for interactive typing. For piped input in scripts, 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.

Python
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))
Output
'Python 是一个非常好的语言。\n是的,的确非常好!!\n'
29
Always pass encoding='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.

Python
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())
Output
line1
6
3
1 line1
2 line2
3 line3

pickle 模块

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.

Python
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))
Output
{'name': 'BackendWiki', 'tags': ['python', 'db'], 'n': 3}
True
True [1, 2, 3]
Use JSON for cross-language or long-lived data. 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.

Python
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}|")
Output
a b c
a-b-c
no newline -> continued
hello

'hello\n'
left    |   right|  mid   |

Friends & Partners