为什么会抛出类型错误?

2024-06-13 01:38:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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: coercing to Unicode: need string or buffer, file found

Tags: 文件importtxttruenewifopencon
1条回答
网友
1楼 · 发布于 2024-06-13 01:38:18

^{}函数接受文件名,即字符串,而不是打开的文件对象。你知道吗

以下应起作用:

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

注意,这里不需要使用== True;这是完全多余的,甚至容易出错。你知道吗

相关问题 更多 >