下面的代码应该删除文件的内容并写入用户通过终端输入的新字符串,但实际上它只会将新行添加到已存在的内容中。我似乎无法使用truncate()
完全删除内容。我该怎么做?
注意:必须使用truncate()
,因为这是本书的练习,我不想跳到未来并使用更高级的东西。
谢谢!
from sys import argv
script, filename, user_name = argv
print("Hi my dear %s... I hope you're doing great today\n" % user_name)
print("We're going to write a string to a file %r\n" % filename)
open_file = open(filename, 'r+')
print("%s, this is what currently file %r has" % (user_name, filename))
read_file = open_file.read()
print("File's content is:\n", read_file)
quote = "To create, first sometime you need to destroy"
print("\n\nAs a quote from your favourite movie says: \n\n %r" \
% quote)
print("So, we will delete the content from the file %r" \
% filename)
open_file.truncate()
print("This is the file %r now" % filename)
print(read_file)
new_line = input("Now let's write something, please start here... ")
print("now %s, let's add this line to the same file %r" \
% (user_name, filename))
open_file.write(new_line)
print("Closing the file")
open_file.close()
print(read_file)
open_file.close()
答案 0 :(得分:2)
truncate()
在当前位置截断。传递一个大小使其将文件截断为该大小。
答案 1 :(得分:1)
truncate
方法有一个可选的size
参数,默认为文件指针的当前位置。由于您已经在文件上调用了read
,truncate
没有做任何事情,因为当前位置是文件的结尾。
将您的通话更改为truncate(0)
,它会清除该文件。