简体   繁体   中英

Finding all numbers in txt filename and sum them. Python

I have to find all numbers in filenames of multiples txt files in a specific directory and add them. How I have to do that? :) I tried this code:

import glob, os
os.chdir("mydirectory")
for filename in glob.glob("*.txt"):
    re.findall(r"\d+", filename)
    print(filename)
re.findall(r"\d+", file) 

but it found only the last filename numbers.

Just create a list and append the numbers of all files. The rest of the code you already have.

import re
os.chdir("mydirectory")

numbers = []

for filename in glob.glob("*.txt"):

    # extract the numbers using regex and append in numbers list
    numbers += re.findall(r"\d+", filename)

print(numbers)

numbers = map(int, numbers) # convert strings to numbers

print(sum(numbers)) # sum them and print the values

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