文件指针和写入操作
文件指针位置
-
w
模式:- 打开文件时,文件指针位于文件的开头。
- 如果文件已存在,文件内容会被清空。
- 写入的数据会从文件开头开始覆盖原有内容。
-
a
模式:- 打开文件时,文件指针位于文件的末尾。
- 如果文件已存在,文件内容不会被清空。
- 写入的数据会追加到文件末尾。
-
r+
模式:- 打开文件时,文件指针位于文件的开头。
- 文件内容不会被清空。
- 写入的数据会从文件开头开始覆盖原有内容,但不会清空文件。
-
r+
模式结合seek
方法:- 可以通过
seek
方法移动文件指针到任意位置。 - 写入的数据会从当前文件指针的位置开始覆盖原有内容。
- 可以通过
示例代码
w
模式:清空文件并从开头写入
with open('output.txt', 'w') as output_file:output_file.write('Hello, World!')
a
模式:追加数据到文件末尾
with open('output.txt', 'a') as output_file:output_file.write('Hello, World!')
r+
模式:从文件开头写入
with open('output.txt', 'r+') as output_file:output_file.write('Hello, World!')
r+
模式结合 seek
方法:从指定位置写入
with open('output.txt', 'r+') as output_file:output_file.seek(5) # 移动文件指针到第5个字符位置output_file.write('World!')
具体示例
假设 output.txt
文件初始内容为 Hello, Python!
,我们使用 r+
模式结合 seek
方法从第5个字符位置开始写入数据:
with open('output.txt', 'r+') as output_file:output_file.seek(5) # 移动文件指针到第5个字符位置output_file.write('World!')
执行上述代码后,output.txt
文件的内容将会是:
Hello, World!
总结
w
模式:清空文件并从开头写入。a
模式:追加数据到文件末尾。r+
模式:从文件开头写入,但不会清空文件。r+
模式结合seek
方法:从指定位置写入。