2014-02-22 45 views
0

我试图让我的python文件将数字保存到文本文件中,但是当我尝试它时它总是空白。我以前做过这么多次,但这次拒绝工作。为什么我的文件在python中显示空白?

openfile = 'example' 
total = 0.5 #another example 
totalstr = str(total) 
file = open("%s.txt" % (openfile), "w") 
file.write(totalstr) 
file.close 
+0

为什么文件行缩进? – BitNinja

+2

它是'.close()',你错过了'()';) – zhangxaochen

+0

在'openfile = file'中将文件作为字符串'file' – ganesshkumar

回答

2

“文件” 是一个标准的Python类型。你想重新命名一些东西。我也假设“openfile”应该是你想要使用的字符串文件名。到目前为止的答案都是正确的,但将它们放在一起给出:

my_file_name = "myfile" 
total = 0.5 
my_file_handle = open("%s.txt" %(my_file_name), "w") 
my_file_handle.write(str(total)) 
my_file_handle.close() 
0

这个工作对我来说:

openfile = "file" 
total = 0.5 
totalstr = str(total) 
file = open("%s.txt" % (openfile), "w") 
file.write(totalstr) 
file.close() 

看看你是否能发现变化。

1

file是python中的关键字。所以,

print '%s' %(file) 

打印

<type 'file'> 

你应该使用:

openfile = 'file' 
相关问题