The Epic Gamer
The Epic Gamer

Reputation: 51

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

How can I copy a file to another file?

The code I’m using is:

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

Which gives the error:

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

How do I fix this error?

Upvotes: 5

Views: 14174

Answers (2)

Taku
Taku

Reputation: 33734

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())

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

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

Upvotes: 11

Salil Deshpande
Salil Deshpande

Reputation: 105

str = FileX.readLines()

FileY.write(str)

, pass string instead of the File

Upvotes: -3

Related Questions