元组中仅打印一个元素

时间:2019-03-17 20:38:12

标签: python for-loop tuples

“ stock_list”元组中有多个项目(打印其中一些以供参考),但是在运行for循环时,仅第一个项目被打印。

以下是输出:

库存清单: ['G:\ ML \ Investing \ intraQuarter / _KeyStats \ a','G:\ ML \ Investing \ intraQuarter / _KeyStats \ aa','G:\ ML \ Investing \ intraQuarter / _KeyStats \ aapl','G:\ ML \ Investing \ intraQuarter / _KeyStats \ abbv','G:\ ML \ Investing \ intraQuarter / _KeyStats \ abc','G:\ ML \ Investing \ intraQuarter / _KeyStats \ abt”,“ G:\ ML \ Investing \ intraQuarter / _KeyStats \ ace”,“ G:\ ML \ Investing \ intraQuarter / _KeyStats \ aci”,“ G:\ ML \ Investing \ intraQuarter / _KeyStats \ acn']

each_dir: G:\ ML \ Investing \ intraQuarter / _KeyStats \ a

import pandas as pd
import os
import time
import datetime as datetime

path = "G:\ML\Investing\intraQuarter"

def Key_Stats(gather="Total Debt/Equity (mrq)"):
    statspath = path+'/_KeyStats'
    stock_list = [x[0] for x in os.walk(statspath)]
    print(stock_list[1:10])

    for each_dir in stock_list[1:]:
        print(each_dir)
        each_file = os.listdir(each_dir)
        ticker = each_dir.split("_KeyStats\\")[1]

        if len(each_file) > 0:
            #parsing time from the html file
            for file in each_file:    
                date_stamp = time.strptime(file, '%Y%m%d%H%M%S.html')
                unix_time = time.mktime(date_stamp)
                #print(date_stamp, unix_time)
                full_file_path = each_dir+'/'+file
                source = open(full_file_path, 'r').read()
                value = source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
                #print(ticker+":", value)
                #time.sleep(15)
                return



Key_Stats()

1 个答案:

答案 0 :(得分:1)

函数定义最后一行的return位于for循环内,因此,该函数将在第一次迭代时返回,并且永远不会发生进一步的迭代。实际上,在python中,您无需在函数末尾编写return,它会默认返回None

或更改标识:

def Key_Stats(gather="Total Debt/Equity (mrq)"):
    statspath = path+'/_KeyStats'
    stock_list = [x[0] for x in os.walk(statspath)]
    print(stock_list[1:10])

    for each_dir in stock_list[1:]:
        print(each_dir)
        each_file = os.listdir(each_dir)
        ticker = each_dir.split("_KeyStats\\")[1]

        if len(each_file) > 0:
            #parsing time from the html file
            for file in each_file:    
                date_stamp = time.strptime(file, '%Y%m%d%H%M%S.html')
                unix_time = time.mktime(date_stamp)
                #print(date_stamp, unix_time)
                full_file_path = each_dir+'/'+file
                source = open(full_file_path, 'r').read()
                value = source.split(gather+':</td><td class="yfnc_tabledata1">')[1].split('</td>')[0]
                #print(ticker+":", value)
                #time.sleep(15)
    return