共计 1102 个字符,预计需要花费 3 分钟才能阅读完成。
在编程过程中,文件操作是非常常见的任务。Python 提供了简洁易用的文件操作接口,可以方便地实现文件的读写与管理。
- 打开文件
使用open()函数可以打开一个文件:
f = open("example.txt", "r") # "r" 表示只读模式
常见模式有:
"r":只读模式(默认)"w":写入模式(会覆盖原有内容)"a":追加模式(在文件末尾追加内容)"rb"/"wb":二进制读写模式
- 读取文件内容
f = open("example.txt", "r")
content = f.read() # 读取整个文件
print(content)
f.close()
还可以逐行读取:
f = open("example.txt", "r")
for line in f:
print(line.strip())
f.close()
- 写入文件
f = open("output.txt", "w")
f.write("Hello, Python!\n")
f.write(" 写入新的一行 \n")
f.close()
如果要在文件末尾追加内容,可以用 "a" 模式:
f = open("output.txt", "a")
f.write(" 追加的内容 \n")
f.close()
- 使用 with 管理文件
为了避免忘记关闭文件,可以使用with语句,它会在代码块结束后自动关闭文件:
with open("example.txt", "r") as f:
content = f.read()
print(content)
写入文件时同样适用:
with open("output.txt", "w") as f:
f.write(" 这是使用 with 写入的内容 ")
- 读取指定字节数
with open("example.txt", "r") as f:
print(f.read(10)) # 读取前 10 个字符
- 读取到列表
with open("example.txt", "r") as f:
lines = f.readlines()
print(lines)
- 文件指针操作
文件读写时有一个“指针”,可以用seek()移动位置,用tell()获取位置:
with open("example.txt", "r") as f:
print(f.read(5)) # 读取前 5 个字符
print(f.tell()) # 显示当前位置
f.seek(0) # 移动到开头
print(f.read(5))
总结:
文件操作在 Python 中非常直观,掌握 open()、read()、write() 和 with 语句的用法是后续处理数据文件的基础。
练习与思考:
- 创建一个
data.txt文件,写入 5 行文本,然后逐行读取并打印。 - 尝试读取一个大文件,只输出前 20 个字符。
- 编写一个程序,将用户输入的内容不断追加到
log.txt文件中。
正文完