2016-02-18 32 views
0

我有以下代码:的raw_input的Python的文件写入

print "We're going to write to a file you'll be prompted for" 
targetfile = raw_input('Enter a filename: ') 
targetfilefound = open('targetfile' , 'w') 
print "What do we write in this file?" 
targetfilefound.write("hello this is working!") 
targetfilefound.close() 

我创建的脚本应该能够写入到用户的raw_input通过定义文件。以上可能是核心问题,可以提出建议。

+2

''targetfile''是不一样'targetfile' –

+0

取下变量'引号targetfile'像这个'targetfilefound = open(targetfile,'w')' – Forge

+0

谢谢你们,这已经纠正了这个问题。 – nick064

回答

0

通过脚本打印你的东西来看可能要用户输入什么应该被打印到文件,以便:

print "We're going to write to a file you'll be prompted for" 
targetfile = raw_input('Enter a filename: ') 
targetfilefound = open(targetfile , 'w') 
print "What do we write in this file?" 
targetfilefound.write(raw_input()) 
targetfilefound.close() 

注意:此方法将创建如果新文件它不存在。如果您想检查文件是否存在,你可以使用os模块,像这样:

import os 

print "We're going to write to a file you'll be prompted for" 
targetfile = raw_input('Enter a filename: ') 
if os.path.isfile(targetfile) == True: 
    targetfilefound = open(targetfile , 'w') 
    print "What do we write in this file?" 
    targetfilefound.write(raw_input()) 
    targetfilefound.close() 
else: 
    print "File does not exist, do you want to create it? (Y/n)" 
    action = raw_input('> ') 
    if action == 'Y' or action == 'y': 
     targetfilefound = open(targetfile , 'w') 
     print "What do we write in this file?" 
     targetfilefound.write(raw_input()) 
     targetfilefound.close() 
    else: 
     print "No action taken" 
0

正如其他人指出的那样,从目标文件中删除引号,因为您已经将其分配给变量。

但实际上,而不是写的代码,你可以用开放使用下面

with open('somefile.txt', 'a') as the_file: 
    the_file.write('hello this is working!\n') 

给出在上述情况下,你不需要做任何异常处理,而处理文件。当发生错误时,文件游标对象会自动关闭,我们不需要明确地关闭它。即使写入文件成功,它也会自动关闭文件指针引用。

Explanation of efficient use of with from Pershing Programming blog

+0

很有意思,谢谢! – nick064

+0

nick064,如果你喜欢这个答案,你可以为它投票 –

+0

没有代表,将返回时,我可以:) – nick064