在python 3.6中截断数据后,我试图从外部文件(test.txt)打印数据
但是,当我在使用 write() 写入后尝试使用 open() 和 read() 执行此操作时,它不起作用。
from sys import argv
script,filename=argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
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 the three lines.")
line1=input("line 1: ")
line2=input("line 2: ")
line3=input("line 3: ")
print("I'm going to write these to the file")
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
a=input("Please type the filename once again:")
b=open(a)
c=b.read()
print(c)
print("And finally, we close it.")
target.close()
不确定,我做错了什么?
Python 不会立即写入文件,而是将它们保存在文件缓冲区中。Python 2 的行为在 Python 3 中继续,其中flush
在文件句柄上调用函数将导致它写入文件(根据此 Python 2.6 问题)
进行此更改应该会导致您想要的行为:
target.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
target.flush()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句