简体   繁体   English

Python-何时写入文件

[英]Python - when does it write to the file

Learning python now. 现在学习python。 I have the following program. 我有以下程序。

  1. Why doesn't the program print anything after the last line? 为什么程序在最后一行之后不打印任何内容? It looks like "target" doesn't have any value that was written. 看起来“目标”没有任何写入的值。 (even if I open the actual file, there are no values why is that? (即使我打开了实际文件,也没有值,为什么呢?

  2. I tried adding that line above the "target.close" thinking the the file doesn't get written on until that line. 我尝试在“ target.close”上方添加该行,以为该文件直到该行才被写入。 That did not work either. 那也不起作用。 so what is the purpose of "target.close"? 那么“ target.close”的目的是什么?

  3. how is that "target.truncate()" gets effect right away. “ target.truncate()”如何立即生效。 After that command, and the script pauses on an input, if I open the file, I can see all the data it had has been erased away. 执行完该命令后,脚本在输入上暂停,如果打开文件,则可以看到已删除的所有数据。

from sys import argv
script, filename = argv

print (f"We are going to erase {filename}")
print ("If you don't want that, press CTRL + C")
print ("if you want that, press ENTER")
input("?  ")

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

print("Truncating the file....")
target.truncate()
print("Finished Truncating")

print("Gimme 3 lines...")

Line1 = input("Line 1:  ")
Line2 = input("Line 2:  ")
Line3 = input("Line 3:  ")

print("Writing these lines to the file")

target.write(Line1 + "\n")
target.write(Line2 + "\n")
target.write(Line3 + "\n")


print ("Finally, we close it")
target.close

input("Do you want to read the file now?")
print(target.read())
target.close

is missing the () call parenthesis. 缺少()调用括号。 That is why nothing is written. 这就是为什么什么都没写的原因。

Then if you want to read the file, you will need to reopen it: 然后,如果您想读取文件,则需要重新打开它:

print(open(filename).read())

Solution

target.close is missing a parenthesis, ie it should be target.close() . target.close缺少括号,即应为target.close()

But looking at your intention, it seems that you want to do target.flush() because you are also attempting target.read() soon after - you'll be unable to read from the file if you closed it. 但是,从您的意图来看,您似乎想执行target.flush()因为您也在不久之后尝试了target.read() -如果关闭该文件,您将无法读取该文件。

Why does it happen 为什么会发生

By default a certain amount of data that is written to the file is actually stored into a buffer - in memory - before it is actually written to the file. 默认情况下,实际写入文件之前,一定数量的已写入文件的数据实际上会存储到缓冲区(内存中)中。 If you want to update the file immediately, you'll need to call the flush method, ie target.flush() Calling target.close() will automatically flush the data that has been buffered, hence why target.close() also updates the file similar to target.flush() . 如果要立即更新文件,则需要调用flush方法,即target.flush()调用target.close()会自动刷新已缓冲的数据,因此为什么target.close()也会更新与target.flush()类似的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM