Python 写入txt文档时的奇怪序列

Python 写入txt文档时的奇怪序列,python,txtwrite,Python,Txtwrite,大家好,这是我第一次来这里,我是Python的初学者。我正在编写一个程序,该程序基于包含另一个包含公司名称的TXT文档(CopyListScript)的输入返回包含股票信息的TXT文档(观察列表信息.txt)。p> 为了实现这一点,我编写了3个函数,其中2个函数reuters\u ticker()和stock\u price()如下所示: def reuters\u ticker(所需搜索): #从公司名称执行谷歌搜索并返回路透社股票代码 尝试: 从谷歌搜索导入搜索 除恐怖外: 打印('没有找到

大家好,这是我第一次来这里,我是Python的初学者。我正在编写一个程序,该程序基于包含另一个包含公司名称的TXT文档(CopyListScript)的输入返回包含股票信息的TXT文档(观察列表信息.txt)。p> 为了实现这一点,我编写了3个函数,其中2个函数
reuters\u ticker()
stock\u price()
如下所示:

def reuters\u ticker(所需搜索):
#从公司名称执行谷歌搜索并返回路透社股票代码
尝试:
从谷歌搜索导入搜索
除恐怖外:
打印('没有找到名为google的模块')
查询=所需搜索+“路透社”
对于搜索中的j(查询,tld=“com.sg”,num=1,stop=1,pause=2):
结果=j
ticker=re.search(r'\w+\.\w+$,结果)
返回ticker.group()
股票价格:

def股价(公司,单据=无):
股票代码=路透社股票代码(公司)
请求https://www.reuters.com/companies/“+股票代码
raw\u main=pd.read\u html(请求)
数据1=原始主数据[0]
数据1.设置索引(0,原地=真)
data1=data1.transpose()
数据2=原始主数据[1]
数据2.设置索引(0,就地=真)
data2=data2.transpose()
库存信息=pd.concat([data1,data2],轴=1)
如果doc==无:
打印(公司+“\n”)
打印('Previous Close:'+str(库存信息['Previous Close'][1]))
打印('远期市盈率:'+str(股票信息['远期市盈率][1]))
打印('股息收益率(%):'+str(股票信息['股息(收益率%)][1]))
其他:
起始日期时间导入日期
将打开的(文件“a”)作为输出:
output.write(date.today().strftime(“%d/%m/%y”)+'\t'+str(股票信息['上一次收盘][1])+'\t'+str(股票信息['远期市盈率][1])+'\t'+'\t'+str(股票信息['股息(收益率][1])+'\n')
output.close()
第三个函数,
watchlist\u report()
,就是我在按所需格式编写信息时遇到问题的地方

def监视列表_报告(监视列表):
将open(watchlist,'r')作为公司,open('watchlist Info.txt,'a')作为输出:
搜索=公司。读取()
x=搜索。拆分('\n')
对于x中的i:
output.write(i+':\n')
股票价格(i,doc='Watchlist Info.txt')
output.write(“\n”)
当我运行
watchlist\u report('watchlist.txt')
,其中watchlist.txt在新行中分别包含“Apple”和“Facebook”,我的输出如下:

26/04/20    275.03  22.26       1.12

26/04/20    185.13  24.72       --

Apple:

Facebook:
而不是基于我在watchlist_report()中编写的代码所希望和期望的:

因此,我的问题是:

1) 为什么我的输出是这样格式化的

2) 我必须更改代码的哪一部分才能以所需的格式生成书面输出


对于如何清理我的代码以及如何使用任何库使我的代码变得更好,我们也非常感谢

您处理两个不同的文件句柄-您的
监视列表_报告
中的文件句柄较早关闭,因此在关闭、刷新和写入外部函数文件句柄之前,先写入它

传递当前文件句柄,而不是在函数中创建新的
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\u price(公司,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
不要关闭内部函数中的文件句柄,外部函数的上下文处理
和(..)
会为您完成这一任务



文件处理的主要好处是,您
写入(…)
到文件中的内容不必立即放在那里。filehandler选择何时实际将数据持久化到磁盘,最晚的时间是当数据超出范围(上下文处理程序)或其内部缓冲区达到某个阈值时,因此它“认为”现在谨慎地更改磁盘上的数据。有关更多信息,请参阅。

您处理两个不同的文件句柄-您的
监视列表_报告中的文件句柄在关闭、刷新和写入外部函数文件句柄之前先关闭,因此先写入

传递当前文件句柄,而不是在函数中创建新的
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\u price(公司,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
不要关闭内部函数中的文件句柄,外部函数的上下文处理
和(..)
会为您完成这一任务



文件处理的主要好处是,您
写入(…)
到文件中的内容不必立即放在那里。filehandler选择何时实际将数据持久化到磁盘,最晚的时间是当数据超出范围(上下文处理程序)或其内部缓冲区达到某个阈值时,因此它“认为”现在谨慎地更改磁盘上的数据。有关更多信息,请参阅。

我明白了,谢谢您的回答!因此,为了确认我的理解,根据我之前编写的错误格式的代码,watchlist_report()打开watchlist Info.txt,但只在关闭时写入文本,而stock_price()的内部函数(也打开watchlist Info.txt)在执行后立即关闭,导致写入stock_price()首先?@ryan使用上下文handlign和
并将其打开(“bla.txt”,“a”)作为f:…
将在您离开上下文hander
创建的缩进后立即关闭文件。此外,您使用的
output.close()
是超级功能。因此,是的-内部部分打开、写入和关闭一个文件,然后返回到外部部分,并在此时关闭(和写入)。因此顺序颠倒了。我明白了。谢谢你的回答!因此,为了证实我的理解,根据我之前编写的错误格式的代码,watchlist_report()会打开watchlist Info.txt,但只打开