Python - 它什么时候写入文件

问题描述:

现在学习python。 我有以下程序。Python - 它什么时候写入文件

  1. 为什么程序在最后一行之后不打印任何内容? 它看起来像“目标”没有任何写入的值。 (即使我打开实际的文件,有没有值 这是为什么?

  2. 我尝试添加上面的“target.close”的思想的文件不被写入,直到该行线。这并不能工作。 那么什么是“target.close”的目的是什么?

  3. 怎么就是“target.truncate()”取得效果的时候了。该命令后,脚本暂停的输入,如果我打开这个文件,我可以看到它所有的数据已经被删除了。

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()) 
+4

'target.close'不关闭文件; 'target.close()'确实。 –

解决方案

target.close缺少一个括号,即它应该是target.close()

但看着你的意图,看起来你想要做target.flush(),因为你很快就会尝试target.read() - 如果你关闭它,你将无法读取文件。

它为什么会发生

默认情况下,一定量的写入到文件数据的实际存储到一个缓冲 - 内存 - 之前它实际上是写入文件。如果要立即更新文件,则需要调用刷新方法,即target.flush()调用target.close()将自动刷新已缓冲的数据,因此target.close()也会更新文件,类似于target.flush()

target.close 

缺少()呼叫括号。这就是为什么没有写入。

然后,如果你想读的文件,则需要重新打开它:

print(open(filename).read())