实验6:文件读写基本操作
实验目标
掌握文件的基本读写操作(创建、读取、写入、追加)。
理解文件操作中的异常处理。
学会统计文件中的内容(如单词数量、行数等)。
实验内容
任务1:创建和写入文件
创建一个文本文件example.txt。
向文件中写入以下内容:
复制
Hello,World!
Thisisatestfile.
Programmingisfun.
任务2:读取文件内容
读取example.txt文件的所有内容,并打印到控制台。
逐行读取文件内容,并打印每行的行号和内容。
任务3:追加内容到文件
向example.txt文件追加以下内容:
复制
Thislineisappended.
Anotherappendedline.
任务4:统计文件中的单词数量
读取example.txt文件内容。
统计文件中的总单词数,并输出结果。
实验代码示例(以Python为例)
Python复制
#任务1:创建和写入文件
withopen(example.txt,w)asfile:
file.write(Hello,World!\n)
file.write(Thisisatestfile.\n)
file.write(Programmingisfun.\n)
print(文件创建并写入成功!)
#任务2:读取文件内容
print(\n读取文件内容:)
withopen(example.txt,r)asfile:
content=file.read()
print(content)
print(\n逐行读取文件内容:)
withopen(example.txt,r)asfile:
lines=file.readlines()
fori,lineinenumerate(lines,1):
print(f行{i}:{line.strip()})
#任务3:追加内容到文件
withopen(example.txt,a)asfile:
file.write(Thislineisappended.\n)
file.write(Anotherappendedline.\n)
print(\n内容追加成功!)
#任务4:统计文件中的单词数量
print(\n统计文件中的单词数量:)
withopen(example.txt,r)asfile:
content=file.read()
words=content.split()
print(f文件中的单词数量:{len(words)})
实验总结
文件操作的基本方法:
open():打开文件,指定模式(r读取,w写入,a追加)。
write():向文件写入内容。
read():读取文件的全部内容。
readlines():逐行读取文件内容。
split():分割字符串为单词列表。
异常处理:
使用with语句可以自动管理文件的打开和关闭,避免资源泄漏。
在实际应用中,可以添加异常处理(如try-except)来处理文件不存在等错误。
应用场景:
数据存储和读取。
日志记录。
文本处理和分析。