簡體   English   中英

如何在 Python 中將計數器寫入輸出文件?

[英]How to write a counter to an output file in 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

我得到的錯誤說它必須是一個字符串才能寫入輸出文件。 有沒有辦法解決?

嘗試這個:

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

您只能將字符串作為參數傳遞給file.write ,請查看文檔
以下是你如何實現它:

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

注意str()周圍的count 此函數將對象轉換為字符串,請參閱頁面了解更多信息。

HTH。

試試fp.write("count")

write 函數只接受字符串,字符串在引號中,'count' 不是整數,這也是你在運行代碼時遇到錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM