[英]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. 我试图在另一个函数中使用一个函数编写的
.txt
文件,该函数接受类似os.path
的对象。 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
TypeError:预期的str,字节或os.PathLike对象,而不是_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; 文件句柄具有
name
属性,因此,如果您确实要使用它,则可以在myfunction1
使用return (outfile.name)
进行myfunction1
。 or you could use infile = myfunction1(infile, outfile).name
in myfunction2
if that's more suitable for your scenario. 或者
infile = myfunction1(infile, outfile).name
如果更适合您的情况,则可以在myfunction2
使用infile = myfunction1(infile, outfile).name
。 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. 或者,由于返回的是
open
的结果,所以不要再次尝试open
它-只需直接使用返回的文件句柄即可。
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. 总结:
open
一个包含文件名的字符串作为输入,并返回一个文件句柄。 You can retrieve the string which represents the file name of an open file with open(thing).name
. 您可以使用
open(thing).name
检索表示打开文件的文件名的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.