类型错误:write() 参数必须是 str,而不是 _io.TextIOWrapper [英] TypeError: write() argument must be str, not _io.TextIOWrapper

查看:86
本文介绍了类型错误:write() 参数必须是 str,而不是 _io.TextIOWrapper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将文件复制到另一个文件?

How can I copy a file to another file?

我使用的代码是:

FileX = open("X.txt","r")
FileY = open("Y.txt","w")
X = FileX
FileY.write(FileX)
FileX.close()
FileY.close()

哪个给出了错误:

TypeError: write() argument must be str, not _io.TextIOWrapper

我该如何解决这个错误?

How do I fix this error?

推荐答案

FileX 当前是一个文件指针,而不是 X.txt 的上下文.要将 X.txt 中的所有内容复制到 Y.txt,您需要使用 FileX.read() 写入 FileX.read() 的读取内容代码>文件X:

FileX is currently a file pointer, not the context of X.txt. To copy everything from X.txt to Y.txt, you will need to use FileX.read() to write the read content of FileX:

FileY.write(FileX.read())

也许您还应该考虑使用 with 语句,

Perhaps you should also look into using a with statement,

with open("X.txt","r") as FileX, open("Y.txt","w") as FileY:
    FileY.write(FileX.read())
# the files will close automatically

并且根据评论的建议,您应该使用 shutil 用于复制文件和/或目录的模块,

And also as suggested by a comment, you should use the shutil module for copying files and/or directories,

import shutil
shutil.copy('X.txt', 'T.txt')
# use shutil.copy2 if you want to make an identical copy preserving all metadata

这篇关于类型错误:write() 参数必须是 str,而不是 _io.TextIOWrapper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆