通過腳本打印你的東西來看可能要用戶輸入什麼應該被打印到文件,以便:
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