亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

寫入txt文檔時的奇怪序列

寫入txt文檔時的奇怪序列

拉風的咖菲貓 2022-10-25 10:31:29
大家好,這是我第一次來這里,我是 Python 的初學者。我正在編寫一個程序,該程序根據另一個包含公司名稱的 txt 文檔(Watchlist)的輸入,返回一個包含股票信息的 txt 文檔(Watchlist Info.txt)。為此,我寫了3個函數,其中2個函數reuters_ticker(),stock_price()完成如下圖:def reuters_ticker(desired_search):        #from company name execute google search for and return reuters stock ticker    try:        from googlesearch import search    except ImportError:        print('No module named google found')    query = desired_search + ' reuters'    for j in search(query, tld="com.sg", num=1, stop=1, pause=2):         result = j    ticker = re.search(r'\w+\.\w+$', result)    return ticker.group() 股票價格:def stock_price(company, doc=None):    ticker = reuters_ticker(company)    request = 'https://www.reuters.com/companies/' + ticker    raw_main = pd.read_html(request)    data1 = raw_main[0]    data1.set_index(0, inplace=True)    data1 = data1.transpose()    data2 = raw_main[1]    data2.set_index(0, inplace=True)    data2 = data2.transpose()    stock_info = pd.concat([data1,data2], axis=1)    if doc == None:        print(company + '\n')        print('Previous Close: ' + str(stock_info['Previous Close'][1]))        print('Forward PE: ' + str(stock_info['Forward P/E'][1]))        print('Div Yield(%): ' + str(stock_info['Dividend (Yield %)'][1]))    else:        from datetime import date        with open(doc, 'a') as output:            output.write(date.today().strftime('%d/%m/%y') + '\t' + str(stock_info['Previous Close'][1]) + '\t' + str(stock_info['Forward P/E'][1]) + '\t' + '\t' + str(stock_info['Dividend (Yield %)'][1]) + '\n')         output.close()第三個函數watchlist_report()是我在以所需格式編寫信息時遇到問題的地方。因此,我的問題是:1)為什么我的輸出格式是這樣的?2) 我必須更改我的代碼的哪一部分才能以我想要的格式進行書面輸出?關于如何清理我的代碼以及我可以用來使我的代碼更好的任何庫的任何其他建議也非常感謝!
查看完整描述

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 多久刷新一次文件?了解更多信息。


查看完整回答
反對 回復 2022-10-25
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號