Python 中 truncate() 方法的行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26917197/
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-19 01:09:37  来源:igfitidea点击:

Behaviour of truncate() method in Python

pythonfile-io

提问by J82

This is from exercise 16from Zed Shaw's Python tutorials. I'm having a hard time understanding what exactly the truncatefunction does in this case. So the logic is that we open a file and then...shorten it? For what? What exactly is happening here?

这是来自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, 'w')

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 + "\n")

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

采纳答案by abarnert

You're right to be suspicious.

你怀疑是对的。

First, file.truncatedoes this:

首先,file.truncate这样做:

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

截断文件的大小。如果存在可选的size参数,则文件将被截断为(最多)该大小。大小默认为当前位置...

Not quite the same as Zed's description—it only "empties the file" if the current position is the start of the file—but since we just opened the file (and not in amode), the current position is the start, so that isn't relevant. We're truncating to an empty file.

与 Zed 的描述不太一样——如果当前位置是文件的开头,它只会“清空文件”——但是因为我们刚刚打开文件(而不是在a模式下),当前位置是开头,所以不是不相关。我们正在截断到一个空文件。

Which is all well and good, except that openalready does that:

这一切都很好,除了open已经做到了:

The most commonly-used values of mode are 'r'for reading, 'w'for writing (truncating the file if it already exists) …

mode 最常用的值是'r'用于读取、'w'用于写入(如果文件已经存在则截断文件)......

So, we open the file, creating it if it doesn't exist and truncating it to 0 bytes if it does. Then, on the next line, we truncate it to 0 bytes.

因此,我们打开文件,如果它不存在则创建它,如果存在则将其截断为 0 字节。然后,在下一行,我们将其截断为 0 字节。

(That "Truncating the file. Goodbye!" message is pretty misleading, since we've already truncated it. Imagine you put a breakpoint on that line and decided to kill the program before executing it…)

(“截断文件。再见!”消息非常具有误导性,因为我们已经截断了它。想象一下你在该行上放置了一个断点并决定在执行之前终止程序......)

But notice that this isn't some silly mistake by Zed; he appears to have done this specifically to make the point in study drill #5:

但是请注意,这不是 Zed 犯的一些愚蠢的错误;他这样做似乎是为了在学习练习 #5 中强调这一点:

If you open the file with 'w'mode, then do you really need the target.truncate()? Read the documentation for Python's openfunction and see if that's true.

如果你用'w'mode打开文件,那么你真的需要target.truncate()? 阅读 Pythonopen函数的文档,看看是否正确。

回答by derek brown

I am currently going through Zed Shaw's book to. Often. when he gives you problems like these, he is goading you into messing around with the different elements of your code to see what they do. Feel free to delete things like target.truncate() and re-run the program. As abarnert says, there is a way to make truncate only remove a portion of the file. Leaving this hole in your knowledge, as to how to get different results with these two options, is meant to annoy you into doing some independent research. It's a very effective way of infecting the reader with curiosity. Take a look how append works in Python and see if you can make truncate() remove only the last line of your test file. Don't be afraid to break your code. "If you want to increase your success rate, double your failure rate." (Thomas J. Watson, former CEO of IBM)

我目前正在阅读 Zed Shaw 的书。经常。当他给你这样的问题时,他是在刺激你弄乱代码的不同元素,看看它们做了什么。随意删除诸如 target.truncate() 之类的内容并重新运行程序。正如 abarnert 所说,有一种方法可以使 truncate 只删除文件的一部分。在你的知识中留下这个漏洞,关于如何使用这两个选项获得不同的结果,是为了让你做一些独立的研究。这是一种用好奇心感染读者的非常有效的方式。看看 append 在 Python 中是如何工作的,看看是否可以使 truncate() 只删除测试文件的最后一行。不要害怕破坏你的代码。“如果你想提高成功率,就把失败率加倍。” (托马斯·J·沃森,