【问题标题】:Append and Truncating together in Python在 Python 中一起追加和截断
【发布时间】:2016-07-25 16:21:24
【问题描述】:

所以,我正在练习 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()

【问题讨论】:

  • 但是,我从一个空文件开始。我正在使用的文件中有数据。
  • 骗子也一样。完全一样,他们在同一个教程中解决相同的问题。
  • 尝试用filename = "yourfile.txt" 替换脚本中的第三行,看看它是否仍然不起作用。此代码在我运行时可以正常工作。
  • 我尝试用我的文件名替换。但是,我在创建文件时收到错误“NameError: name 'ex16_sample' is not defined”。

标签: python append truncate


【解决方案1】:

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

当您以“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()

【讨论】:

  • 我如上更改了我的代码,它工作了!!!太感谢了。我不知道光标位置并将其设置为 (0, 0)。感谢您的帮助。
  • @Sarat 如果此解决方案适合您,请考虑将其标记为已接受的解决方案。
  • 我该怎么做? - 好的,我点击了绿色箭头 - 我希望就是这样。
【解决方案2】:

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

【讨论】:

  • 如果他只想擦除文件的内容,这有关系吗?
  • 是的。我想理解的是 - 如果我使用“w”而不使用截断,那么无论如何文件都会被截断并重写。那么,如果我使用“a”然后“截断”怎么办!如果 truncate 不需要用 'w' 指定并且不能用 'a' 工作(在我的代码中) - 那么它到底做什么以及如何?
猜你喜欢
  • 2015-03-04
  • 2017-01-08
  • 2011-04-14
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 2013-10-31
相关资源
最近更新 更多