前言
大家好,我是倔强青铜三 。欢迎关注我,微信公众号:倔强青铜三。欢迎点赞、收藏、关注,一键三连!!!
欢迎来到**苦练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='')
最后感谢阅读!欢迎关注我,微信公众号 :
倔强青铜三
。欢迎点赞
、收藏
、关注
,一键三连!