猿问

写入txt文档时的奇怪序列

大家好,这是我第一次来这里,我是 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) 我必须更改我的代码的哪一部分才能以我想要的格式进行书面输出?


关于如何清理我的代码以及我可以用来使我的代码更好的任何库的任何其他建议也非常感谢!


拉风的咖菲猫
浏览 94回答 1
1回答

陪伴而非守候

您处理两个不同的文件句柄 - 您内部的文件句柄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 多久刷新一次文件?了解更多信息。
随时随地看视频慕课网APP

相关分类

Python
我要回答