python - 在python中使用变量创建txt文件

标签 python file

我正在为学校开发一个程序,该程序询问用户想要为文件命名什么,然后我应该写入该文件。

到目前为止我有这个:

dream_file = input("What file name would you like to save the cards? ")
dream_file = open(dream_file, 'w')

dream_file.write(str(dream_hand1))
print(dream_file)

dream_file.close()

当我运行它时,我收到此错误: <_io.TextIOWrapper name='dream' mode='w'encoding='US-ASCII'>

据我所知,该文件永远不会被创建。

最佳答案

文件肯定正在被写入,但正如其他人提到的,您只是打印出文件句柄的 python 表示形式的字符串表示形式。如果您想打印文件内容,只需进行一些更改即可。

# it is poor practice to reuse variable names
# for completely different things. It is best
# to differentiate your file path and the file
# handler itself.
dream_file_path = input("What file name would you like to save the cards? ")

# w+ allows reading and writing of files
dream_file = open(dream_file_path, 'w+')

dream_file.write(str(dream_hand1))

# seek 0 brings you back from where you just
# wrote (end of the file), to the beginning
dream_file.seek(0)

# .read() simply reads the entire file as a string
print(dream_file.read())

dream_file.close()

关于python - 在python中使用变量创建txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51312142/

相关文章:

vb.net - 如何抑制 file.delete 上的错误消息?

Python mod_wsgi 写入自定义日志文件而不是 apache error_log

php - html文件夹外的文件和图像

python - zipfile 无法处理某些类型的 zip 数据?

python - pylab 找不到其模块的引用

java - 有效地存储和查询字符串列表

来自 .txt 文件的 C++ 二维数组

java - 使用 Runtime.exec 未打开我的 xls 文件

python - Sphinx搜索引擎是否正式支持Python API?

python - Django:获取按组分隔的模板的所有权限