在使用此代码进行写文件然后读出来的时候,读出的文件为空
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, 'r+')
print("Truncating the file. Goodbye!")
target.truncate()
print("I'm going to write these to the file.")
target.write("line1")
target.write("\n")
target.write("line2")
target.write("\n")
target.write("line3")
print("Target's content is:")
print(target.read())
print("And finally, we close it.")
target.close()
输出:
C:\Users\Starwaves\Desktop>python pt.py pt_smp.txt
We're going to erase pt_smp.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
I'm going to write these to the file.
Target's content is:
And finally, we close it.
经过排查之后,发现是写入文件之后没有用target.close()
关闭文件,所以写入内容并没有保存,提前先target.close()
了再读取就好了
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, 'r+')
print("Truncating the file. Goodbye!")
target.truncate()
print("I'm going to write these to the file.")
target.write("line1")
target.write("\n")
target.write("line2")
target.write("\n")
target.write("line3")
target.close()
target = open(filename, 'r+')
print("Target's content is:")
print(target.read())
print("And finally, we close it.")
target.close()
输出:
C:\Users\Starwaves\Desktop>python pt.py pt_smp.txt
We're going to erase pt_smp.txt.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
I'm going to write these to the file.
Target's content is:
line1
line2
line3
And finally, we close it.