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

时间:2015-02-27 00:02:52

标签: python python-2.7 powershell

我正在以艰难的方式学习Python 并参与练习16.研究人员说使用readargv编写脚本。

我的代码如下:

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>

我不确定为什么脚本只是打印一个空白文件。

1 个答案:

答案 0 :(得分:3)

你永远调用 writefile.close()方法:

writefile.write(pet_name)
writefile.close
#              ^^

在不关闭文件的情况下,帮助快速写入的内存缓冲区永远不会被刷新,文件实际上仍然是空的。

调用方法:

writefile.write(pet_name)
writefile.close()

或将该文件用作context manager(使用with statement)让Python为您关闭它:

with open(file_name, 'w') as writefile:
    writefile.write(pet_name)

请注意writefile.truncate()来电完全是多余的。以写入模式('w')打开文件始终会截断文件已经