简体   繁体   中英

Using a file returned from a function as an argument for another function in python

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM