# 文件路径可以是相对路径或绝对路径
# 常见模式:'r' 只读,'w' 写入(覆盖),'a' 追加,'b' 二进制
# 打开文件(推荐使用with自动关闭文件)
with open('data.txt', 'r', encoding='utf-8') as f:
# 文件操作
pass
# 传统方式
f = open('data.txt', 'r', encoding='utf-8')
f.close()
'r'
只读'w'
写入(覆盖)'a'
追加写入'b'
二进制模式(如 'rb', 'wb')
with open('data.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
with open('data.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
with open('data.txt', 'r', encoding='utf-8') as f:
first10 = f.read(10) # 读取前10个字符
print(first10)
read()
读取全部readline()
读取一行readlines()
读取所有行为列表
with open('data.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(lines)
with open('output.txt', 'w', encoding='utf-8') as f:
f.write('Hello, world!\n')
with open('output.txt', 'a', encoding='utf-8') as f:
f.write('追加内容\n')
lines = ['第一行\n', '第二行\n', '第三行\n']
with open('output.txt', 'w', encoding='utf-8') as f:
f.writelines(lines)
writelines()
不会自动加换行符,需手动添加。
# 读取图片、音频等二进制文件
with open('image.png', 'rb') as f:
data = f.read()
# 写入二进制文件
with open('copy.png', 'wb') as f:
f.write(data)
FileNotFoundError
PermissionError
UnicodeDecodeError
try:
with open('nofile.txt', 'r', encoding='utf-8') as f:
content = f.read()
except FileNotFoundError:
print('文件不存在!')
def log_message(msg):
with open('log.txt', 'a', encoding='utf-8') as f:
f.write(msg + '\n')
log_message('程序启动')
# 保存和读取用户分数
score = 95
with open('score.txt', 'w', encoding='utf-8') as f:
f.write(str(score))
with open('score.txt', 'r', encoding='utf-8') as f:
saved_score = int(f.read())
print(saved_score)
# 统计文本文件的行数和单词数
def count_file(filename):
lines = 0
words = 0
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
lines += 1
words += len(line.split())
return lines, words
print(count_file('data.txt'))
实现一个工具,支持批量读取多个文本文件,统计每个文件的行数、单词数,并输出总计。
编写一个程序,能够复制任意二进制文件(如图片、音频等)。
实现一个日志分析工具,统计不同类型日志的数量,并生成简单的可视化报表(如文本直方图)。