Python将文件模块导入另一个

时间:2017-02-23 12:23:16

标签: python python-2.7 python-3.x

我正在尝试将名为 log_entry_counts 的变量从名为 data_processed.py 的python文件导入到名为 failed_hmac.py的同一目录中的另一个文件中进行一些百分比计算但导入后,我无法访问导入的模块(文件)中的变量。这是第一个文件名data_processed.py。 进口口 从datetime import datetime,timedelta 来自馆藏进口柜台

def dataCount(folderName):
    #count = 0
    log_entry_counts = Counter()
    today_date = datetime.today()
    date_ranges = [
                    ('30 Days', today_date - timedelta(days=30)),
                   # ('3 months', today-date - timedelta(days=90)),
                    #('year', today-date - timedelta(days=365))
                  ]
    for path, dirs, files in os.walk(folderName):
        for dirname in dirs:
            log_date = (os.path.join(path, dirname))

        for items in files:
            if items != ".DS_Store":
                try:
                    log_date = datetime.strptime(path[39:47], '%m%d%Y')
                    for text, dr in date_ranges:
                        if log_date >= dr:
                            log_entry_counts[text] += 1
                except ValueError:
                    print 'This line has a problem:', log_date

    total = 0

    print log_entry_counts['30 Days'] 

def main():

    filePath = 'file.txt'

    hmacCount(filePath)

if __name__ == "__main__":

    main()

它遍历文件夹并计算所有子文件夹中的文件。另一个文件名failed_hmac.py如下

import os, sys
from datetime import datetime, timedelta
from collections import Counter
import data_processed

def hmacCount(fileName):
    # Get the last failed hmac date
    fileHandle = open('file.txt',"r")
    lineList = fileHandle.readlines()
    fileHandle.close()
    lastLine = lineList[-1]
    lastDate = datetime.strptime(lastLine[:10], '%m/%d/%Y')

    with open(fileName) as f_input:

        logEntryCounts = Counter()

        #today_date = datetime.today() - timedelta(days=14)
                #print today_date
        dateRanges = [
                    ('30 Days', lastDate - timedelta(days=30)),
                    #('3 months', lastDate - timedelta(days=90)),
                    #('One year', lastDate - timedelta(days=330))
                  ]

        for line in f_input:

            #Stop Processing if there are no more lines
            if not line:

                break

            if "Following hmac" in line:

                try:
                    logDate = datetime.strptime(line[:10], '%m/%d/%Y')

                    for text, dr in dateRanges:

                        if logDate >= dr:

                            logEntryCounts[text] += 1

                except ValueError:

                    print 'This line has a problem:', logDate

    total = 0

    hmacData = float(logEntryCounts['30 Days'])

    print logEntryCounts['30 Days']

# Call The function
def main():

    filePath = 'file.txt'

    hmacCount(filePath)

if __name__ == "__main__":

    main()  

目标是将 data_processed.py 导入 failed_hmac.py 并使用变量 logEntryCounts log_entry_counts 执行一些百分比计算,但我一直 logEntryCounts 未定义错误

1 个答案:

答案 0 :(得分:0)

data_entry_logsdata_processed.py中函数内的变量。您必须修改代码才能调用函数data_processed.dataCount()并返回值,以便您可以使用该变量。

data_processed.py

def dataCount(folderName):
    #your code
    return log_entry_counts

failed_hmac.py

替换

hmacData = float(logEntryCounts['30 Days'])

hmacData = float(data_processed.dataCount(...)['30 Days'])

另一种方法,我认为更清洁的方法是在类中声明这两个函数,如this question.

中所指定的