【问题标题】:Python: TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'str'Python:TypeError:+的不支持的操作数类型:'_io.TextIOWrapper'和'str'
【发布时间】:2018-12-13 10:43:21
【问题描述】:

我想做的事:

我想打印一个文件名。我可以看到输出文件可用。但我无法单独打印文件名。

Python 代码:

today=datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
string_file="string_"+today+".csv"
outputFile = open(string_file_rdkb, "w")
#....some code here...
my_df=pd.DataFrame(datalist2)
my_df.to_csv(outputFile, index=False, header=False)
print(outputFile + " is generated") #Here is the issue

输出显示:

print(outputFile + " is generated")
TypeError: unsupported operand type(s) for +: '_io.TextIOWrapper' and 'str'

我试图解决的问题:

print(str(outputFile) + " is generated")

输出显示:

<_io.TextIOWrapper name='string_20181213-160004.csv' mode='w' encoding='cp1252'> is generated

预期输出:

string_20181213-160004.csv is generated

【问题讨论】:

  • 我想你想打印变量string_file,它是一个字符串,而不是outputFile,它是一个打开的文件对象。
  • 打印文件name string_file而不是文件对象怎么样?
  • 我现在明白了!

标签: python python-3.x


【解决方案1】:

只需使用:print(outputFile.name + " is generated")

【讨论】:

  • @DipankarNalui 如果您发现解决方案很好且有帮助,您应该支持它们。
【解决方案2】:

尝试使用您定义的变量string_file,因为这只是字符串格式的文件名;

today=datetime.datetime.today().strftime("%Y%m%d-%H%M%S")
string_file="string_"+today+".csv"
outputFile = open(string_file_rdkb, "w")
#....some code here...
my_df=pd.DataFrame(datalist2)
my_df.to_csv(outputFile, index=False, header=False)
print(string_file+ " is generated") #Here is the issue

输出:

>>> string_20181213-160004.csv is generated

您之前打印的是文件 object,它是在文件名上调用 open() 的结果,因此它返回的是对象本身,而不仅仅是名称。

【讨论】:

  • io.TextIOWrapper 有一个完全代表它的属性时,为什么要使用自创变量。
  • 因为已经创建了变量以用于分配给outputFile。无论哪种方式都是可以接受的,事实上这种形式更清晰。
  • 我知道,但是使用 object 属性更直接
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-12
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-05
相关资源
最近更新 更多