首页 > 解决方案 > 类型错误:参数 1 必须是字符串或只读字符缓冲区,而不是文件(在 Learn python the Hard 的练习 17 中)

问题描述

copying from test.txt to new1_file.txt
 The input file is 8 bytes long
 Does the output file exists, True
 readyy, hit RETURN to continue, CTRL-C to abort

Traceback (most recent call last):
File "ex17a.py", line 18, in <module>
   out_file.write(indata) 
TypeError: argument 1 must be string or read-only character buffer, not file

这是我使用的代码

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)

indata = open(from_file,'r')

print " The input file is %d bytes long" % len(from_file)

print " Does the output file exists, %r" %exists(to_file)
print " readyy, 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()
indata.close()

标签: python

解决方案


indata在您的行out_file.write(indata)中是一个文件对象。获取其内容调用indata.read()

out_file.write(indata.read())

推荐阅读