繁体   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