You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

《笨办法学Python》练习17遇TypeError:参数需为字符串或只读字符缓冲区

解决TypeError: argument 1 must be string or read-only character buffer, not file问题

嘿,这个错误的根源其实很好揪出来——你把文件对象直接传给了write()方法,但它要的是文件里的实际内容呀!

让我给你拆解问题和修复方案:

错误原因

你写的indata = open(from_file,'r')只是完成了打开文件的操作,得到的是一个文件对象,而不是文件里的文本内容。out_file.write()方法需要的是字符串(或者字节缓冲区),所以自然会抛出TypeError。

修复步骤

  1. 读取文件内容:打开文件后,必须调用read()方法来获取文件里的内容,把文件对象转换成字符串:

    # 替换原来的indata = open(from_file,'r')
    in_file = open(from_file, 'r')
    indata = in_file.read()
    

    这样indata就变成了文件里的实际文本,write()就能正常处理了。

  2. 修正文件长度计算的小错误:你代码里的len(from_file)是在计算文件名的字符长度,不是文件内容的字节数,这和你打印的提示文字不符。改成len(indata)就能正确显示输入文件的大小了。

修正后的完整代码

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "copying from %s to %s" % (from_file, to_file)
# 正确打开并读取文件内容
in_file = open(from_file, 'r')
indata = in_file.read()
# 正确计算文件内容长度
print " The input file is %d bytes long" % len(indata)
print " Does the output file exists: %r" % exists(to_file)
print " Ready, hit RETURN to continue, CTRL-C to abort"
raw_input()

out_file = open(to_file, 'w')
out_file.write(indata)

print " Alright, all done"
# 记得关闭文件
out_file.close()
in_file.close()

更优雅的写法(推荐)

用Python的with语句管理文件,它会自动帮你关闭文件,避免忘记关闭的问题:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "copying from %s to %s" % (from_file, to_file)

# with语句自动管理文件生命周期
with open(from_file, 'r') as in_file:
    indata = in_file.read()

print " The input file is %d bytes long" % len(indata)
print " Does the output file exists: %r" % exists(to_file)
print " Ready, hit RETURN to continue, CTRL-C to abort"
raw_input()

with open(to_file, 'w') as out_file:
    out_file.write(indata)

print " Alright, all done"

内容的提问来源于stack exchange,提问作者Harshdeep Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:44:26