Python - 什么时候写入文件
Python - when does it write to the file
正在学习python。
我有以下程序。
为什么程序在最后一行之后不打印任何内容?
看起来 "target" 没有写入任何值。
(即使我打开实际文件,也没有值
这是为什么?
我尝试在 "target.close" 上方添加该行,认为直到该行才写入文件。那也不管用。
那么"target.close"的目的是什么?
怎么"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())
target.close
缺少 ()
调用括号。这就是为什么什么都不写的原因。
那么如果你想读取这个文件,你需要重新打开它:
print(open(filename).read())
解决方案
target.close
缺少括号,即它应该是 target.close()
.
但是从你的意图来看,你似乎想做 target.flush()
因为你也在尝试 target.read()
不久之后 - 如果你关闭它你将无法从文件中读取.
为什么会这样
默认情况下,写入文件的一定数量的数据在实际写入文件之前实际上存储在缓冲区中 - 在内存中。如果要立即更新文件,则需要调用flush方法,即target.flush()
调用target.close()
会自动刷新已缓冲的数据,因此target.close()
也会更新类似于 target.flush()
.
的文件
正在学习python。 我有以下程序。
为什么程序在最后一行之后不打印任何内容? 看起来 "target" 没有写入任何值。 (即使我打开实际文件,也没有值 这是为什么?
我尝试在 "target.close" 上方添加该行,认为直到该行才写入文件。那也不管用。 那么"target.close"的目的是什么?
怎么"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())
target.close
缺少 ()
调用括号。这就是为什么什么都不写的原因。
那么如果你想读取这个文件,你需要重新打开它:
print(open(filename).read())
解决方案
target.close
缺少括号,即它应该是 target.close()
.
但是从你的意图来看,你似乎想做 target.flush()
因为你也在尝试 target.read()
不久之后 - 如果你关闭它你将无法从文件中读取.
为什么会这样
默认情况下,写入文件的一定数量的数据在实际写入文件之前实际上存储在缓冲区中 - 在内存中。如果要立即更新文件,则需要调用flush方法,即target.flush()
调用target.close()
会自动刷新已缓冲的数据,因此target.close()
也会更新类似于 target.flush()
.