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
Solution 1:
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,
withopen("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
Solution 2:
str = FileX.readLines()
FileY.write(str)
, pass string instead of the File
Post a Comment for "Typeerror: Write() Argument Must Be Str, Not _io.textiowrapper"