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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4562100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:19:44  来源:igfitidea点击:

Why truncate when we open a file in 'w' mode in python

python

提问by Animesh

I am going through Zed Shaw's Python Book. I am currently working on the opening and reading files chapters. I am wondering why we need to do a truncate, when we are already opening the file in a 'w' mode?

我正在阅读 Zed Shaw 的 Python Book。我目前正在研究打开和阅读文件章节。我想知道为什么我们需要进行截断,当我们已经以“w”模式打开文件时?

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

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

采纳答案by ismail

It's redundant since, as you noticed, opening in write mode will overwrite the file. More information at Input and Outputsection of Python documentation.

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

回答by Keith

That's just a reflection of the standard posix semantics. see man fopen(3). Python just wraps that.

这只是标准 posix 语义的反映。参见 man fopen(3)。Python 只是包装了它。

回答by Lennart Regebro

So Zed Shaw calls truncate() on a file that is already truncated. OK, that's pretty pointless. Why does he do that? Who knows!? Ask him!

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

Maybe he does it to show that the method exists? Could be, but that would be pretty daft, since I've never needed to truncate a file in my 15 years as a programmer so it has no place in a newbie book.

也许他这样做是为了表明该方法存在?可能是,但这会很愚蠢,因为在我作为程序员的 15 年里,我从来没有需要截断文件,所以它在新手书中没有位置。

Maybe he does it because he thinks he has to truncate the file, and he simply isn't aware that it's pointless?

也许他这样做是因为他认为他必须截断文件,而他根本不知道这是毫无意义的?

Maybe he does it intentionally to confuse newbies? That would fit with his general modus operandi, which seems to be to intentionally piss people off for absolutely no reason.

也许他是故意混淆新手的?这符合他的一般作案手法,这似乎是毫无理由地故意惹恼人们。

Update:The reason he does this is now clear. In later editions he lists this question as a "common question" in the chapter, and tells you to go read the docs. It's hence there to:

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

  1. Teach you to read the documentation.
  2. Understand every part of code you copy paste from somewhere before you copy-paste it.
  1. 教你阅读文档。
  2. 在复制粘贴之前,了解从某处复制粘贴的代码的每一部分。

You can debate if this is good teaching style or not, I wouldn't know.

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

The number of "Help I don't understand Zed Shaws book"-questions on SO had dwindled, so I can't say that it's any worse than any other book out there, which probably means it's better than many. :-)

“帮助我不明白 Zed Shaws 的书”——SO 上的问题已经减少了,所以我不能说它比任何其他书都差,这可能意味着它比很多书都好。:-)

回答by Dch47

If you would READ the questions before asking it, he answers it for you:

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

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 readand argvto 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 line3with 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.

额外的信用:“如果你觉得你不明白这一点,回到过去并使用评论技巧让它在你的脑海中得到解决。每行上方一个简单的英文评论将帮助你理解,或者至少让你知道你的意思需要更多的研究。

编写一个类似于上一个练习的脚本,使用readargv读取您刚刚创建的文件。

这个文件重复太多了。使用字符串,格式和逃逸打印出来line1line2line3只有一个 target.write()命令,而不是6。

找出为什么我们必须将 a'w'作为额外参数传递才能打开。提示: open 试图通过让你明确地说你想写一个文件来确保安全。

如果你用'w'mode打开文件,那么你真的需要 target.truncate()?

去阅读 Python 的 open 函数的文档,看看这是否属实。” - Zed Shaw

He explicitly wants you to find these things out for yourself, this is why his extra credit is important.

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

He also EXPLICITLY states that he wants you to PAY ATTENTION TO DETAIL. Every little thing matters.

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

回答by Kristin Gannon

With truncate(), you can declare how much of the file you want to remove, based on where you're currently at in the file. Without parameters, truncate()acts like w, whereas w always just wipes the whole file clean. So, these two methods canact identically, but they don't necessarily.

使用truncate(),您可以根据您当前在文件中的位置声明要删除的文件数量。没有参数,truncate()就像 w 一样,而 w 总是把整个文件擦干净。因此,这两种方法可以起到相同的作用,但不一定。

回答by Bruno Bronosky

While it's not useful to truncate when opening in 'w' mode, it is useful in 'r+'. Though that's not the OP's question, I'm going to leave this here for anyone who gets lead here by Google as I did.

虽然在 'w' 模式下打开时截断没有用,但它在 'r+' 中很有用。虽然这不是 OP 的问题,但我将把这个留给像我一样被谷歌领导的任何人。

Let's say you open (with mode 'r+', remember there is no 'rw' mode) a 5 line indented json file and modify the json.load-ed object to be only 3 lines. If you target.seek(0)before writing the data back to the file, you will end up with 2 lines of trailing garbage. If you target.truncate()it you will not.

假设您打开(使用模式 'r+',记住没有 'rw' 模式)一个 5 行缩进的 json 文件并将json.load-ed 对象修改为只有 3 行。如果您target.seek(0)在将数据写回文件之前,您将得到 2 行尾随垃圾。如果你target.truncate()它你不会。

I know this seems obvious, but I'm here because I am fixing a bug that occurred after an object that stayed the exact same size for years... shrank because of a signing algorithm change. (What is not obvious is the unit tests I had to add to prevent this in the future. I wrote my longest docstring ever explaining why I'm testing signing with 2 ridiculously contrived algorithms.)

我知道这似乎很明显,但我在这里是因为我正在修复一个错误,该错误是在对象多年来保持完全相同的大小之后发生的……由于签名算法更改而缩小。(不太明显的是我必须添加单元测试以防止将来发生这种情况。我写了我最长的文档字符串,解释了为什么我要使用 2 个可笑的人为设计的算法测试签名。)

Hope this helps someone.

希望这可以帮助某人。

回答by YATIN GUPTA

When you open a file in write mode, you truncate the original (everything that was there before is deleted). Then whatever you write is added to the file. The problem is, write wants to add information from the beginning, and raises an IOError when the pointer is left at the end. For this type of writing you want to use append (open the file with the 'a+' argument).

当您以写入模式打开文件时,您会截断原始文件(之前存在的所有内容都将被删除)。然后你写的任何内容都会添加到文件中。问题是, write 想从头开始添加信息,当指针留在最后时引发 IOError 。对于这种类型的写作,您要使用 append(用 'a+' 参数打开文件)。

回答by 1UC1F3R616

Scenario:
I was making a ransomware and needed to encrypt the file, My aim is not to encrypt the complete file but that much only to corrupt it because I want it to be fast in what it does and so saving time in encrypting it all, so I decided to edit some text only.
Now If I use writethen my purpose is destroyed here because I would have to write the file a to z. Then what can I do?
well here truncatecan be put in use.

场景:
我正在制作一个勒索软件并需要加密文件,我的目标不是加密完整的文件,而只是为了破坏它,因为我希望它能够快速完成它的工作,从而节省加密时间,所以我决定只编辑一些文本。
现在,如果我使用write,那么我的目的就在这里被破坏了,因为我必须将文件 a 写入 z。那我能做什么呢?
那么这里truncate就可以使用了。

Below is my code which just takes a token of last 16 digits in a file:

下面是我的代码,它只需要文件中最后 16 位数字的标记:

with open('saver.txt', 'rb+') as f:
    text_len = len(f.read())
    f.truncate(text_len-16)
    f.close()

I open the file
Truncate only 16 characters from file which will be replaced by me later.
Notice I am using it in read only mode, If I use in write mode than File is truncated completely and it will throw error when our truncate command comes in.
Answering this question after 8.4 years. :)

我打开文件
Truncate only 16 characters from file 稍后将由我替换。
请注意,我在只读模式下使用它,如果我在写入模式下使用,则文件被完全截断,当我们的 truncate 命令进入时它会抛出错误。
8.4 年后回答这个问题。:)