Reputation: 55
I am trying to use a .txt
file written by a function in another function which accepts an os.path
-like object. My problem is when I feed the argument it shows me the error message
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
The following is the simple form of what I am trying to do.
def myfunction1(infile, outfile):
with open(infile, 'r') as firstfile:
#do stuff
with open(outfile, 'w+') as secondfile:
secondfile.write(stuff)
return(outfile)
def myfucntion2(infile, outfile):
infile=myfunction1(infile, outfile)
with open(infile, 'r') as input:
#do stuff
with open (outfile, 'w+') as outfile2:
outfile2.write(stuff)
return(outfile)
Both functions do stuff fine on their own, it's just that I can't seem to feed 2nd function a value from the first.
Upvotes: 0
Views: 509
Reputation: 189397
Your function returns a file handle, not a string.
File handles have a name
attribute, so you could fix it by using return (outfile.name)
in myfunction1
if that's really what you mean; or you could use infile = myfunction1(infile, outfile).name
in myfunction2
if that's more suitable for your scenario. Or, since what is returned is the result from open
, just don't attempt to open
it a second time -- just use the returned file handle directly.
input=myfunction1(infile, outfile)
#do stuff
with open (outfile, 'w+') as outfile2 ...
In summary: open
wants a string containing a file name as its input, and returns a file handle. You can retrieve the string which represents the file name of an open file with open(thing).name
.
Upvotes: 1