1 回答

TA貢獻1757條經驗 獲得超8個贊
您處理兩個不同的文件句柄 - 您內部的文件句柄watchlist_report較早關閉,因此在外部函數文件句柄關閉、刷新和寫入之前先寫入。
不要在你的函數中創建一個新的,而是open(..)傳遞當前文件句柄:
def watchlist_report(watchlist):
with open(watchlist, 'r') as companies, open('Watchlist Info.txt', 'a') as output:
searches = companies.read()
x = searches.split('\n')
for i in x:
output.write(i + ':\n')
stock_price(i, doc = output) # pass the file handle
output.write('\n')
在里面def stock_price(company, doc=None):使用提供的文件句柄:
def stock_price(company, output = None): # changed name here
# [snip] - removed unrelated code for this answer for brevity sake
if output is None: # check for None using IS
print( ... ) # print whatever you like here
else:
from datetime import date
output.write( .... ) # write whatever you want it to write
# output.close() # do not close, the outer function does this
不要關閉內部函數中的文件句柄,with(..)外部函數的上下文處理會為您完成。
文件處理的主要內容write(..)是不必立即將您放入文件的內容放置在那里。文件處理程序選擇何時將數據實際保存到您的磁盤,它所做的最新操作是當它超出(上下文處理程序的)范圍或當其內部緩沖區達到某個閾值時,因此它“認為”現在謹慎地更改為光盤上的數據。請參閱python 多久刷新一次文件?了解更多信息。
添加回答
舉報