Python正在读取文件,但命令行打印一个空行

Python正在读取文件,但命令行打印一个空行,python,python-2.7,powershell,Python,Python 2.7,Powershell,我正在努力学习Python,我正在练习16。这项研究训练要求使用read和argv编写脚本 我的代码如下: from sys import argv script, file_name, pet_name = argv print "Ah, your pet's name is %r." %pet_name print "This will write your pet's name in a text file." print "First, this will delete the fi

我正在努力学习Python,我正在练习16。这项研究训练要求使用
read
argv
编写脚本

我的代码如下:

from sys import argv

script, file_name, pet_name = argv

print "Ah, your pet's name is %r." %pet_name
print "This will write your pet's name in a text file."
print "First, this will delete the file. "
print "Proceeding..."

writefile = open(file_name, 'w')
writefile.truncate()
writefile.write(pet_name)
writefile.close

raw_input("Now it will read. Press ENTER to continue.")

readfile = open(file_name, "r")
print readfile.read()
代码一直工作到最后。当它说要打印文件时,命令行给出一个空行

PS C:\Users\[redacted]\lpthw> python ex16study.py pet.txt jumpy
Ah, your pet's name is 'jumpy'.
This will write your pet's name in a text file.
First, this will delete the file.
Proceeding...
Now it will read. Press ENTER to continue.

PS C:\Users\[redacted]\lpthw>
我不知道为什么脚本只是打印一个空白文件。

您从未调用过
writefile.close()
方法:

writefile.write(pet_name)
writefile.close
#              ^^
在不关闭文件的情况下,用于帮助加快写入速度的内存缓冲区永远不会被刷新,并且文件实际上保持为空

调用以下方法之一:

writefile.write(pet_name)
writefile.close()
或者将该文件用作(与的)命令Python为您关闭它:

with open(file_name, 'w') as writefile:
    writefile.write(pet_name)
请注意,
writefile.truncate()
调用是完全冗余的。以写模式打开文件(
'w'
)总是会截断已存在的文件