通过脚本打印你的东西来看可能要用户输入什么应该被打印到文件,以便:
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"
''targetfile''是不一样'targetfile' –
取下变量'引号targetfile'像这个'targetfilefound = open(targetfile,'w')' – Forge
谢谢你们,这已经纠正了这个问题。 – nick064