代码示例库

搜索、筛选并收藏你需要的 Python 代码片段。

重置
#入门 #字符串 #数字 #列表 #列表 #循环 #切片 #if #列表 #字典 #字典 #while #while #函数 #函数 #类 #类 #文件 #异常 #测试 #测试 #Pygame #Pygame #matplotlib #随机漫步 #CSV #API #Django #Django #Django

文件读写

第10章 文件和异常

演示读取与写入文件。

# 读取
with open("pi_digits.txt") as file:
    contents = file.read()
print(contents)

# 逐行读取
with open("pi_digits.txt") as file:
    for line in file:
        print(line.rstrip())

# 写入(覆盖)/ 追加
with open("programming.txt", "w") as file:
    file.write("我喜欢编程。\n")
with open("programming.txt", "a") as 
...