在 Python 中一起追加和截断

Append and Truncating together in Python

所以,我正在学习 Zed Shaw Python 书中的练习 16。

我想在同一个文件上尝试追加和截断。我知道,这没有意义。但是,我是新手,我正在尝试了解如果同时使用两者会发生什么。

所以,首先我以附加模式打开文件,然后截断它,然后写入它。

但是,截断在这里不起作用,我写的任何内容都会附加到文件中。

那么,有人可以解释为什么截断不起作用吗?尽管我首先以追加模式打开文件,但我相信我之后调用了 truncate 函数,它应该可以正常工作!!!

以下是我的代码:

from sys import argv

script, filename = argv

print "We're going to erase %r." %filename
print "If you don't want that. hit CTRL-C (^C)."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename, 'a')

print "Truncating the file. Goodbye!"
target.truncate()

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."


target.write(line1 + "\n" + line2 + "\n" + line3)

print "And finally, we close it."
target.close()

参数 'a' 打开文件进行追加。您将需要改用 'w'

Truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position.

当您使用'a'模式打开文件时,位置在文件的结尾

你可以这样做

f = open('myfile', 'a')
f.tell()  # Show the position of the cursor
# As you can see, the position is at the end
f.seek(0, 0) # Put the position at the begining
f.truncate() # It works !!
f.close()