在python中以“w”模式打开文件时为什么要截断

2024-06-01 00:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在翻阅赛德肖的Python书。我目前正在工作,打开和阅读文件章节。我想知道,当我们已经以“w”模式打开文件时,为什么需要进行截断?

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

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

Tags: 文件thetarget模式openfilenamefileprint
3条回答

这是多余的,因为正如您所注意到的,以写模式打开将覆盖文件。更多信息请参见Python文档的^{}部分。

如果你在提问前先阅读问题,他会为你回答:

Extra Credit: " If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand, or at least let you know what you need to research more.

Write a script similar to the last exercise that uses read and argv to read the file you just created.

There's too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of 6.

Find out why we had to pass a 'w' as an extra parameter to open. Hint: open tries to be safe by making you explicitly say you want to write a file.

If you open the file with 'w' mode, then do you really need the target.truncate()?

Go read the docs for Python's open function and see if that's true." - Zed Shaw.

他明确地希望你自己找出这些东西,这就是为什么他的额外功劳是重要的。

他还明确表示希望你注意细节。每件小事都很重要。

所以Zed Shaw对已经被截断的文件调用truncate()。好吧,那太没意义了。他为什么这么做?谁知道!?问他!

也许他这样做是为了证明这种方法的存在?可能是,但那是相当愚蠢的,因为在我15年的程序员生涯中,我从来没有需要截断一个文件,所以它在新手书中没有位置。

也许他这样做是因为他认为他必须截断文件,而他只是不知道这是没有意义的?

也许他是故意迷惑新手?这与他通常的作案手法是一致的,他似乎故意无缘无故地激怒人们。

更新:他这样做的原因现在已经清楚了。在以后的版本中,他在章节中将这个问题列为“常见问题”,并告诉您去阅读文档。因此它可以:

  1. 教你阅读文档。
  2. 在复制粘贴之前,请先了解从某个位置复制粘贴的代码的每个部分。

我不知道这是不是好的教学风格,你可以争论一下。

“帮助我不懂泽德·肖斯的书”的数量在减少,所以我不能说它比其他任何一本书都差,这可能意味着它比许多书都好。:-)

相关问题 更多 >