在 Python 中,输入和输出(I/O)操作是非常基础且重要的功能。它们允许程序与用户交互,读取用户提供的数据,并向用户展示结果。Python 提供了简单易用的内置函数来处理标准输入和输出。
1. 输入
input()
函数
input()
函数用于从标准输入(通常是键盘)读取一行文本,并返回一个字符串。你可以将这个字符串转换为其他类型的数据,比如整数或浮点数。
语法:
input([prompt])
prompt
是一个可选参数,表示提示信息,可以是任何字符串,用来告知用户应该输入什么内容。
示例:
# 读取用户的姓名
name = input("请输入您的名字: ")
print(f"你好, {name}!")
# 读取并转换为整数
age = int(input("请输入您的年龄: "))
print(f"您将在 {age + 1} 岁庆祝生日。")
# 读取并转换为浮点数
height = float(input("请输入您的身高(米): "))
print(f"您的身高是 {height:.2f} 米。")
2. 输出
print()
函数
print()
函数用于将信息输出到标准输出(通常是屏幕)。它可以输出多个值,并支持格式化字符串。
语法:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
*objects
:要打印的对象,可以是一个或多个,之间用逗号分隔。sep
:指定对象之间的分隔符,默认为空格' '
。end
:指定行尾字符,默认为换行符'\n'
。file
:指定输出目标,默认是sys.stdout
(标准输出),也可以是文件对象。flush
:是否立即刷新输出缓冲区,默认为False
。
示例:
# 打印简单的文本
print("Hello, world!")
# 打印多个值
print("Name:", "Alice", "Age:", 30)
# 自定义分隔符和结束字符
print("apple", "banana", "cherry", sep=", ", end="!\n")
# 使用 f-string 格式化输出
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
# 打印到文件
with open('output.txt', 'w') as f:
print("This will be written to a file.", file=f)
3. 文件 I/O
除了标准输入和输出外,Python 还提供了丰富的文件操作功能。你可以使用内置的 open()
函数来打开文件,并使用 read()
, write()
, close()
等方法进行文件读写操作。
打开文件
file = open('filename.txt', mode='r', encoding='utf-8')
filename
:文件名或路径。mode
:文件打开模式,常见的有:'r'
:只读模式(默认)。'w'
:写入模式,如果文件存在则覆盖,不存在则创建。'a'
:追加模式,文件指针指向文件末尾,新内容添加在文件末尾。'x'
:创建模式,如果文件已存在则抛出错误。'b'
:二进制模式,通常与上述模式组合使用,如'rb'
表示以二进制方式读取文件。't'
:文本模式(默认),通常与上述模式组合使用,如'rt'
表示以文本方式读取文件。
encoding
:指定文件编码,默认为平台默认编码,常用的是'utf-8'
。
读取文件
# 读取整个文件内容
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 按行读取文件
with open('example.txt', 'r') as file:
for line in file:
print(line.strip()) # strip() 去除每行末尾的换行符
# 读取特定数量的字符
with open('example.txt', 'r') as file:
partial_content = file.read(10) # 读取前10个字符
print(partial_content)
写入文件
# 写入文本
with open('output.txt', 'w') as file:
file.write("This is a new line.\n")
file.write("This is another line.")
# 追加文本
with open('output.txt', 'a') as file:
file.write("This line is appended to the file.\n")
# 使用 writelines() 写入多行
lines = ["First line\n", "Second line\n", "Third line\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)
关闭文件
使用 with
语句打开文件时,Python 会在代码块结束后自动关闭文件。如果你不使用 with
语句,则需要显式调用 close()
方法来关闭文件:
file = open('example.txt', 'r')
content = file.read()
file.close()
4. 标准错误输出
有时你可能希望将错误信息输出到标准错误流(stderr
),而不是标准输出流(stdout
)。这可以通过 sys.stderr
来实现。
import sys
print("This is an error message", file=sys.stderr)
5. 格式化输出
Python 提供了多种格式化输出的方式,包括:
- f-string:这是最简洁和推荐的方式,使用
f
或F
作为字符串前缀,并在字符串中使用{}
插入变量。
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
str.format()
:使用format()
方法进行格式化。
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {1}".format(name, age)) # 使用索引
print("Name: {n}, Age: {a}".format(n=name, a=age)) # 使用关键字
- 百分号格式化:这是一种较老的格式化方式,使用
%
操作符。
print("Name: %s, Age: %d" % (name, age))
总结
Python 的输入输出功能非常强大且易于使用。通过 input()
和 print()
函数,你可以轻松地与用户进行交互;通过 open()
函数,你可以方便地进行文件读写操作。格式化输出则让你能够更灵活地控制输出的内容和格式。