【问题标题】:counter on for loop, reporting 1for循环计数器,报告1
【发布时间】:2019-04-01 14:41:02
【问题描述】:

我只是想在我的for 循环周围添加一个计数器,以计算每个包含“VCCS”的条件在我的目录中有多少文件......逻辑适用于迭代,因为它是遍历我的目录我有一个文件的次数......但是我的计数器一直在报告 1. 相关行是 files_in_directory market 和评论 # here

我在 PyLint 中收到此警告:Constant name "files_in_directory" doesn't conform to UPPER_CASE naming stylepylint(invalid-name) , on files_in_directory = 0

我已经尝试将 set 0 移到 for 上方并尝试一下,有什么想法吗?

if __name__ == "__main__":
    try:
        currentDT = datetime.datetime.now()
        files_in_directory = 0 # here
        for filename in os.listdir(config.DIRECTORY_LOCATION):
            if filename.__contains__('VCCS'):
                old_stdout = sys.stdout
                log_file = open("./logs/metrics.log","w")
                sys.stdout = log_file
                files_in_directory += 1 # here

                PENDING_RECORDS = FindPendingRecords().get_excel_data()
                # Do operations on PENDING_RECORDS

                # Reads excel to map data from excel to vital
                MAP_DATA = FindPendingRecords().get_mapping_data()

                # Configures Driver
                VITAL_ENTRY = VitalEntry()

                # Start chrome and navigate to vital website
                VITAL_ENTRY.instantiate_chrome()

                # Begin processing Records
                VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA)

                print(f"Date: ")
                print (str(currentDT))                
                print(f"Files in Directory #{files_in_directory}") # here

                sys.stdout = old_stdout
                log_file.close()  

    except Exception as exc:
        # print(exc)
        raise

【问题讨论】:

  • 您不需要将log_file 附加到sys.stdout,因为print 需要file kwarg: print('some string', file=log_file)
  • 我无法用一个简单的例子来复制你的问题:import os; my_count=0; for file in os.listdir(os.getcwd()): if file.__contains__('.txt.'): my_count+=1; print(f"{my_count}")
  • 我已经尝试将集合 0 移到 for 上方并尝试如果您在 for 循环中将计数重置为 0,那肯定会 让它每次都报告1
  • @C.Nivs 不,它也只报告了 1 个。
  • 是否有任何东西在修改/使用global files_in_directory?我不确定它会在哪里重置

标签: python for-loop if-statement counter


【解决方案1】:

注意:为了可读性,这是为了代替许多 cmets

您的问题不是 MCVE。为了使其更简洁并确定确切原因:

import os

if __name__ == "__main__":
    # Remove try block, just let it raise an error
    my_counter = 0

    for file in os.listdir("some_directory"):
        # you don't need to call the __contains__ method
        # as the 'in' keyword will invoke that for you
        if "VCCS" in file:

            # increment your counter first
            my_counter += 1
            print(file, my_counter)

现在毫无疑问是什么在修改my_counter,这将打印出您正在查看的文件,并在计数器旁边。

一旦你消除了这种行为,你就可以开始添加你的其他功能

import os

if __name__ == "__main__":
    # Remove try block, just let it raise an error
    my_counter = 0

    for file in os.listdir("some_directory"):
         if 'VCCS' in file:
             my_counter += 1
             print(my_counter, file)

             # Add functions back in one by one
             PENDING_RECORDS = FindPendingRecords().get_excel_data()

继续此过程,直到您确定是什么导致您的行为。就目前而言,我没有看到任何可能覆盖该计数器变量的明确内容,因此我怀疑 A)您发布的代码确实 not 反映了正在运行的内容或 B)您正在修改/resetting files_in_directory 模块中的其他位置。

建议编辑:

我建议您添加模块中的其他代码以查看发生了什么。这样我们就可以更清楚地了解您的代码运行时发生的情况

【讨论】:

    【解决方案2】:

    首先要做的是:您确定您传递了正确的目录,并且该目录确实包含多个文件,其文件名中包含 VCCS?

    我还会尝试在不使用 Try/Except 块的情况下运行此代码,以查看在第一次增量后是否没有出现错误。

    LMK 你得到了什么,我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2020-05-31
      • 2010-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多