苦练Python第45天:使用open函数读取文件内容

前言

大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!

欢迎来到**苦练Python第 45 天!**今天掌握开发者必备神技------用 open() 安全、高效地读取任何文件。


📥 1. open() 基础语法

python 复制代码
file = open("文件名.txt", "模式")

常用模式

  • "r" 只读(默认)
  • "w" 写入(覆盖)
  • "a" 追加
  • "b" 二进制(图片等)
  • "t" 文本(默认)

别忘了 关闭 文件:

python 复制代码
file = open("sample.txt", "r")
content = file.read()
file.close()

📄 2. 一口气读完

python 复制代码
with open("sample.txt", "r") as f:
    data = f.read()
    print(data)

✅ with 语句自动关闭文件,出异常也不怕。


📜 3. 逐行读取

readline() 一次一行

python 复制代码
with open("sample.txt", "r") as f:
    line = f.readline()
    while line:
        print(line.strip())
        line = f.readline()

readlines() 一次全部行 → 列表

python 复制代码
with open("sample.txt", "r") as f:
    lines = f.readlines()
    print(lines)

📏 4. 读取指定字符数

python 复制代码
with open("sample.txt", "r") as f:
    first_10_chars = f.read(10)
    print(first_10_chars)

🔄 5. 文件对象可迭代

大文件省内存写法:

python 复制代码
with open("sample.txt", "r") as f:
    for line in f:
        print(line.strip())

🧨 6. 异常安全处理

python 复制代码
try:
    with open("non_existent.txt", "r") as f:
        data = f.read()
except FileNotFoundError:
    print("文件不存在!")
except IOError:
    print("读取错误!")

🛠️ 实战:统计文件词数

python 复制代码
with open("sample.txt", "r") as f:
    text = f.read()
    words = text.split()
    print("总词数:", len(words))

📌 小结

  • 用 open(filename, "r") 读取
  • with open() 自动关闭
  • read() / readline() / readlines() 灵活切换
  • 用 try-except 捕获异常
  • 迭代文件对象,大文件也流畅

🧪 练习任务

1. 读取文件并统计:总行数、总词数、总字符数

python 复制代码
# 使用 open() 统计 sample.txt 的行数、词数、字符数
with open("sample.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()          # 读取所有行到列表

total_lines = len(lines)           # 行数
# 合并所有行再拆分单词,防止行尾空格影响
total_words = len("".join(lines).split())
total_chars = sum(len(line) for line in lines)  # 每行字符数累加

print(f"总行数: {total_lines}")
print(f"总词数: {total_words}")
print(f"总字符数: {total_chars}")

2. 只打印包含 "ERROR" 的日志行

python 复制代码
# 使用 open() 逐行读取 log.txt,仅输出包含 ERROR 的行
with open("log.txt", "r", encoding="utf-8") as f:
    for line in f:                 # 逐行迭代,节省内存
        if "ERROR" in line:
            print(line.rstrip())   # rstrip() 去掉右侧换行与空格

3. 读取文件并倒序输出所有行

python 复制代码
# 使用 open() 将 sample.txt 的所有行倒序打印
with open("sample.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()   # 读取全部行

lines.reverse()             # 就地反转列表
for line in lines:
    # 行末自带换行符,end='' 防止 print 再加一次
    print(line, end='')

最后感谢阅读!欢迎关注我,微信公众号 :倔强青铜三。欢迎 点赞、收藏、关注,一键三连!

相关推荐
VIP_CQCRE1 小时前
GPT Image 2.6 商品图换背景后悬浮?接触阴影、透明区域与反射验收
图像处理·人工智能·ai·电商
wuyk5551 小时前
Python办公自动化-第01讲-环境搭建与自动化认知
python·自动化·pyqt
泯泷2 小时前
别再傻傻地喂文件了,大厂都在偷偷给AI建这种“专属图书馆”
人工智能
oak隔壁找我2 小时前
一款运行在 DSH(DeepSeek Harness)中的类 Postman HTTP 接口调试插件
人工智能·程序员
高洁012 小时前
数字孪生与计算机视觉:让机器看懂现场
人工智能·python·机器学习·transformer·迁移学习
ComPDFKit2 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
Csvn3 小时前
如果明天供应商涨价 3 倍?三层解耦,换模型只改一行配置(C05)
人工智能·aigc·agent
在所不辞兄4 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
yz_aiks4 小时前
Termux 使用教程:把安卓手机变成随身 Linux(装 Python、SSH 远程、跑自动化脚本)
android·linux·python·智能手机·ssh·termux
锋行天下4 小时前
langgraph 全栈项目(三)
前端·人工智能·后端