【发布时间】: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需要filekwarg: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