使用python中的变量创建txt文件

时间:2018-07-12 18:18:24

标签: 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名称='dream'模式='w'编码='US-ASCII'>

据我所知文件从未创建过。

3 个答案:

答案 0 :(得分:0)

这不是错误。错误将带有清晰的错误消息,并且将具有堆栈跟踪以及代码行和其他内容。我认为这里拥有的就是您要做的事情

print(dream_file)

该语句不打印文件内容。实际上,它不能,因为您是以write模式打开文件。而是打印dream_file的字符串表示形式,它是类型_io.TextIOWrapper的对象。如果要打印刚放入文件中的字符串,可以改为

print(str(dream_hand1))

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

答案 1 :(得分:0)

您的文件是通过使用打开功能中的'w'创建的,“ <_io.TextIOWrapper name ='dream'mode ='w'encoding ='US-ASCII'>“来自{{1 }}这意味着dream_file是_io.textIOWrapper对象。

检查python所在的目录,您应该找到一个输入时命名的文件,其中包含print(dream_file)数据。

答案 2 :(得分:0)

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