2014-11-25 37 views
-3

這是我到目前爲止的代碼,如果沒有辦法寫它,我只需要將它轉換爲字符串? (很抱歉,如果這是一個愚蠢的問題,我是新來的編碼)如何寫一個計數器到python的輸出文件

outfile = input("What would you like the text file index's name to be?") 

if os.path.isfile(outfile): 
    print("Name already used, please choose another") 
else: 
    fp = open(outfile, 'w') 
    fp.write(count) 
    fp.write(wordCount) 
    fp.close 

我得到的錯誤說,它必須寫入到輸出文件中的字符串,反正是有解決這個?在此先感謝您的幫助:)

+0

嘗試類型轉換爲字符串寫入(str(count))和write(str(wordCount))。 – 2014-11-25 11:36:15

+0

什麼計數存儲,是變量或你只是想寫數文件???,因爲我不能看到計數decleared之前? – Hackaholic 2014-11-25 11:48:02

回答

0

您只能將字符串作爲參數傳遞給file.write,請看docs
這裏是你如何可以實現它:

with open(outfile, "w") as fp: 
    fp.write(str(count)) 
    fp.write(str(wordcount)) 

str()周圍count。此功能將對象轉換爲字符串,有關更多信息,請參閱this頁面。

HTH。

0

試試這個:

with open(outfile, "w") as fp: 
    fp.write(str(count)) 
    fp.write(str(wordcount)) 
-2

嘗試fp.write("count")

寫函數只有字符串,字符串是在引號和「數」不是整數也被爲什麼在運行代碼時出現錯誤?

相關問題