关于Python中write()和truncate()的问题

1 投票
3 回答
10438 浏览
提问于 2025-04-16 15:24

我在Mac的终端上,正在学习如何打开、关闭、读取和删除文件。

当我设置了

f = open("sample.txt", 'w')

然后按下 f.truncate(),文件里的内容就被删除了。

但是,当我使用 f.write() 时,文本文件并没有更新。只有在我执行 f.truncate() 之后,它才会更新。

我在想这是为什么(我以为 f.truncate() 是用来删除文本的呢!)?为什么在我输入 f.write() 时,文本编辑器不会自动更新呢?

3 个回答

2

为了提高性能,写入文件时会使用缓存。这意味着数据可能不会立即写入文件,直到你明确告诉它“现在把缓存的数据写入磁盘”。通常我们会用 flush() 来做到这一点。而 truncate() 在截断文件之前,显然也会先把缓存的数据写入。

4

让我们来看一个例子:

import os
# Required for fsync method: see below

f = open("sample.txt", 'w+')
# Opens sample.txt for reading/writing
# File pointer is at position 0

f.write("Hello")
# String "Hello" is written into sample.txt
# Now the file pointer is at position 5

f.read()
# Prints nothing because file pointer is at position 5 & there
# is no data after that

f.seek (0)
# Now the file pointer is at position 0

f.read()
# Prints "Hello" on Screen
# Now the file pointer is again at position 5

f.truncate()
# Nothing will happen, because the file pointer is at position 5
# & the truncate method truncate the file from position 5.     

f.seek(0)
# Now the file pointer  at position 0

f.truncate()
# Trucate method Trucates everything from position 0
# File pointer is at position 0

f.write("World")
# This will write String "World" at position 0
# File pointer is now at position 5     

f.flush()
# This will empty the IOBuffer
# Flush method may or may not work depends on your OS 

os.fsync(f)
# fsync method from os module ensures that all internal buffers
# associated with file are written to  the disk

f.close()
# Flush & close the file object f
4

f.write() 是用来往 Python 程序的内部缓存里写数据的,跟 C 语言里的 fwrite() 函数类似。不过,数据并不会立刻被送到操作系统的缓存里,只有当你调用 f.flush()f.close(),或者缓存满了的时候,数据才会被送过去。一旦这样做了,其他应用程序就能看到这些数据了。

需要注意的是,操作系统还有一层缓存,这个缓存是所有正在运行的应用程序共享的。当文件被刷新时,数据会写入这些缓存,但还没有写入到硬盘上,直到过了一段时间,或者你调用 fsync()。如果你的操作系统崩溃或者电脑断电,这些未保存的更改就会丢失。

撰写回答