为什么会抛出类型错误?

时间:2014-11-03 19:17:37

标签: python terminal typeerror

import filecmp

user = 't'
con = open(user + '.txt','a')
new = open(user + 'newfile.txt','a')
if filecmp.cmp(con, new) == True:
   print('good')
else:
    print('bad')

文件t.txt和tnewfile.txt都包含字母w。 为什么会抛出TypeError?

TypeError: coercing to Unicode: need string or buffer, file found

1 个答案:

答案 0 :(得分:3)

filecmp.cmp()函数采用文件名称,即字符串,而不是打开文件对象。

以下内容应该有效:

user = 't'
con = user + '.txt'
new = user + 'newfile.txt'
if filecmp.cmp(con, new):
    print('good')
else:
    print('bad')

请注意,您无需在此处使用== True;这完全是多余的,甚至容易出错。

相关问题