【问题标题】:creating a txt file using a variable in python在python中使用变量创建一个txt文件
【发布时间】:2018-07-12 18:18:24
【问题描述】:

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

到目前为止,我有这个:

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">

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

【问题讨论】:

  • 什么是dream_hand1?您确定这是您的全部相关代码吗?
  • 什么是dream_hand1?
  • 这是一个我必须写入文件的变量。
  • 其余代码在一个函数中。好像太长了,我不能发布整个内容。
  • &lt;_io.TextIOWrapper name='dream' mode='w' encoding='US-ASCII'&gt; 不是错误;这是print(dream_file)的输出

标签: python file


【解决方案1】:

一个文件肯定正在被写入,但正如其他人所提到的,您只是打印出文件句柄的 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()

【讨论】:

  • 我们还没有了解“seek”,所以我无法使用它。
  • 'w' 打开一个文件进行写入,'w+' 打开一个文件进行读写。
  • 没问题。尽管您说您还没有学过,但您的教授不太可能认为您在作弊或在 python 中对文件使用 .seek() 方法。 Seek 只是文件句柄的少数常用方法之一,包括 read、readlines、write、writelines 和 seek,所有这些在 python io 文档中都有很好的描述:docs.python.org/3/tutorial/inputoutput.html。如果明确禁止任何尚未教授的内容,那么好吧,但使用 .seek() 不太可能引起任何作弊嫌疑。
【解决方案2】:

这不是错误。一个错误会带有一个明确的错误消息,它会有一个堆栈跟踪,以及代码行和诸如此类的东西。我认为你在这里所拥有的就是你这样做时所得到的

print(dream_file)

该语句不打印文件内容。事实上,它不能,因为您正在以write 模式打开文件。相反,它打印dream_file 的字符串表示形式,它是_io.TextIOWrapper 类型的对象。如果你想打印刚刚放入文件的字符串,你可以这样做

print(str(dream_hand1))

尝试在您的代码所在的文件夹中查找新文件,或探索 python 的input and output 功能以更好地了解其工作原理。

【讨论】:

    【解决方案3】:

    您的文件是在 open 函数中使用 'w' 创建的,“<_io.textiowrapper name="dream" mode="w" encoding="US-ASCII">”来自print(dream_file),这意味着dream_file 是一个 _io.textIOWrapper 对象。

    检查你的python所在的目录,你应该找到一个名为你输入的文件,里面有dream_hand1数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 2020-11-09
      • 2020-06-27
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      相关资源
      最近更新 更多