AITC Wiki

Python 文件读写

Python File I/O

Python 文件读写

English version: O

文件的读取与写入,以及通过控制台捕获用户输入。

写入与读取文件

Python 提供内置函数进行文件操作。with 语句确保文件在使用后正确关闭。

# 写入文件
with open("file.txt", "w") as f:
    f.write("Hello, Python!")
 
# 读取文件
with open("file.txt", "r") as f:
    content = f.read()  # "Hello, Python!"
print(type(content), content)

用户输入

input() 函数暂停执行并从用户读取一行文本。返回的值始终是字符串。

nam = input('what is your name?')
print('Welcome', nam)  # Welcome <你的输入>

字符串格式化

Python 提供多种格式化输出字符串的方式:

f-strings(Python 3.6+)

name = "Alice"
print(f"Hello, {name}!")  # Hello, Alice!
num = 2
print(f'Hello,{name}! num={num}#')

format() 方法

print("Value: {}".format(10))  # Value: 10

简单拼接

print('value:', name, '!', 'key:', num)  # value: Alice ! key: 2

注释

# 单行注释
 
"""
多行注释
使用三引号(也用于文档字符串)。
"""

Tip

在大多数 IDE 中,可以选中代码行后按 Ctrl + / 快速切换注释。

相关概念

来源资料