2016-02-18 30 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