gpt4 book ai didi

python - for 循环计数器,报告 1

转载 作者:太空宇宙 更新时间:2023-11-03 21:05:11 24 4
gpt4 key购买 nike

我只是想在我的 for 周围添加一个计数器循环,根据 contains ' VCCS 的限定来计算我的目录中有多少个文件'...逻辑正在迭代,因为它正在遍历我的目录,我有一个文件的次数...但是我的计数器不断报告 1。相关行是 files_in_directory市场评论# here .

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

我尝试将集合 0 移到 for 和 try 之上,有什么想法吗?

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

最佳答案

注意:为了可读性,这将取代许多注释

您提出的问题不是 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) 您发布的代码反射(reflect)正在运行的内容或 B) 您正在修改/resetting files_in_directory 模块中其他位置。

建议编辑:

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

关于python - for 循环计数器,报告 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55457758/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com