简体   繁体   中英

Python sum of a for loop

I'm new to programming and I found something what can help in my current job. Program is reading external text files and getting a specific value of time from every file in folder. I've got to the point where I have the output I need but I can't to sum it. It seems like my code returns number for every file separately.

my code:

for filename in glob.glob(os.path.join(path, '*.lst'), recursive=True):
   with open(os.path.join(os.getcwd(), filename), 'r') as f:
        for lines in f:
            if "'INTERNAL_DATA',103,1,'','T','','" in lines:                                                                                         
                workTime = lines.split("'INTERNAL_DATA',103,1,'','T','','")[-1].strip()                                                                              
                workSec = int(workTime[9:11])

                print(workSec)

my result: 
23 
55 
16 
53 
56

...and what I need is the sum of these results. I've tried to sum it with a for loop but it gives the same output. Can someone help me?

You need to add the value to your workSec variable in each loop. You will also need to initialize it to 0 outside the loop so you can use it in the arithmetic expression.

for filename in glob.glob(os.path.join(path, '*.lst'), recursive=True):
   with open(os.path.join(os.getcwd(), filename), 'r') as f:
        workSec = 0
        for lines in f:
            if "'INTERNAL_DATA',103,1,'','T','','" in lines:                                                                                         
                workTime = lines.split("'INTERNAL_DATA',103,1,'','T','','")[-1].strip()                                                                              
                workSec = workSec + int(workTime[9:11])

                print(workSec)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM