0

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.

3
  • 2
    I tried to fix the indentation but that is obviously speculative -- please review. Also I imagine you want to open(infile) not open('infile') in myfunction1`. Commented Jan 8, 2019 at 8:24
  • Also, 2ndfile? That's not a valid variable name. How does that run at all to give you that TypeError? Commented Jan 8, 2019 at 8:27
  • sorry about the typos, tried to write simple version quickly. original code was too long to post. Commented Jan 8, 2019 at 9:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks infile = myfunction1(infile, outfile).name solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.