Python3 提供了简单而强大的输入和输出机制,既支持基本的数据输入输出操作,也支持高级的格式化、文件处理等功能。以下是关于输入和输出的详细讲解。
1. 输入
Python3 的 input()
函数用于从用户获取输入。
1.1 基本用法
input()
会暂停程序,等待用户输入,并将输入的内容作为字符串返回。
示例:
name = input("Enter your name: ") # 提示用户输入
print(f"Hello, {name}!") # 输出用户输入
输出:
Enter your name: Alice
Hello, Alice!
1.2 转换输入类型
input()
返回的始终是字符串,需要使用类型转换函数进行转换。
示例:
age = int(input("Enter your age: ")) # 转换为整数
print(f"You are {age} years old.")
1.3 多个输入
用空格分隔的多个输入:
使用 split()
方法处理用户输入。
values = input("Enter numbers separated by space: ").split()
numbers = [int(v) for v in values]
print("Numbers:", numbers)
用自定义分隔符:
可以用 split(delimiter)
处理。
values = input("Enter numbers separated by comma: ").split(',')
numbers = [int(v) for v in values]
print("Numbers:", numbers)
2. 输出
Python3 使用 print()
函数进行输出。
2.1 基本用法
print()
默认输出内容并换行。
print("Hello, world!")
2.2 指定分隔符
使用 sep
参数自定义输出内容之间的分隔符。
print("Alice", "Bob", "Charlie", sep=", ")
输出:
Alice, Bob, Charlie
2.3 禁用换行
通过设置 end
参数自定义行尾字符(默认是换行符 \n
)。
print("Hello", end=" ")
print("world!")
输出:
Hello world!
2.4 格式化输出
Python 提供了多种格式化输出的方法:
使用 f-string(推荐,Python 3.6+)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
使用 format()
方法
print("My name is {} and I am {} years old.".format("Alice", 25))
print("My name is {0} and I am {1} years old.".format("Alice", 25))
使用 %
格式化字符串
print("My name is %s and I am %d years old." % ("Alice", 25))
2.5 控制宽度与对齐
- 指定宽度:
{value:width}
,默认右对齐。 - 左对齐:
{value:<width}
- 右对齐:
{value:>width}
- 居中对齐:
{value:^width}
print(f"{'Name':<10}{'Age':>5}")
print(f"{'Alice':<10}{25:>5}")
输出:
Name Age
Alice 25
3. 文件输入和输出
Python 提供了内置的文件操作函数,用于文件的读取和写入。
3.1 打开文件
使用 open()
函数打开文件:
file = open("example.txt", mode="r", encoding="utf-8")
- 常见模式:
'r'
:读取(默认)'w'
:写入(会覆盖文件内容)'a'
:追加写入'rb'
/'wb'
:二进制读写
3.2 读取文件
- 按行读取:
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip()) # 去掉换行符
- 读取全部内容:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
- 按固定字节读取:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read(10) # 读取前10个字符
print(content)
3.3 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, world!\n")
file.write("Python file I/O.")
3.4 追加写入
with open("example.txt", "a", encoding="utf-8") as file:
file.write("\nThis is appended text.")
4. 高级 I/O 操作
4.1 文件指针操作
file.seek(offset, whence)
:移动文件指针。whence=0
:从文件开头(默认)whence=1
:从当前位置whence=2
:从文件末尾
with open("example.txt", "rb") as file:
file.seek(5) # 移动到第5个字节
print(file.read(10)) # 读取10个字节
4.2 异常处理
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found!")
4.3 JSON 文件操作
Python 提供了 json
模块用于处理 JSON 格式的文件。
import json
# 写入 JSON
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as file:
json.dump(data, file)
# 读取 JSON
with open("data.json", "r") as file:
content = json.load(file)
print(content)
5. 进阶技巧
5.1 多行输入
可以通过 sys.stdin
或 splitlines()
读取多行输入。
import sys
print("Enter multiple lines (Ctrl+D to end):")
lines = sys.stdin.read().splitlines()
print("You entered:", lines)
5.2 输入/输出重定向
使用 sys.stdout
和 sys.stdin
重定向输入输出。
import sys
# 输出重定向到文件
sys.stdout = open("output.txt", "w")
print("This will be written to the file!")
sys.stdout.close()
如果你对某部分有更多疑问,请随时告诉我! 😊