簡體   English   中英

使用從函數返回的文件作為python中另一個函數的參數

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

我試圖在另一個函數中使用一個函數編寫的.txt文件,該函數接受類似os.path的對象。 我的問題是當我輸入參數時會顯示錯誤消息

TypeError:預期的str,字節或os.PathLike對象,而不是_io.TextIOWrapper

以下是我正在嘗試做的簡單形式。

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)

這兩個函數本身都能很好地完成工作,只是我似乎無法從第一個函數開始為第二個函數提供值。

您的函數返回文件句柄,而不是字符串。

文件句柄具有name屬性,因此,如果您確實要使用它,則可以在myfunction1使用return (outfile.name)進行myfunction1 或者infile = myfunction1(infile, outfile).name如果更適合您的情況,則可以在myfunction2使用infile = myfunction1(infile, outfile).name 或者,由於返回的是open的結果,所以不要再次嘗試open它-只需直接使用返回的文件句柄即可。

input=myfunction1(infile, outfile)
#do stuff
with open (outfile, 'w+') as outfile2 ...

總結: open一個包含文件名的字符串作為輸入,並返回一個文件句柄。 您可以使用open(thing).name檢索表示打開文件的文件名的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM