i have a folder with alot of csv files with different names. i want to work only with the files that their name is made up of numbers only, though i have no information of the range of the numbers in the title of the files.
for example, i have '''file_list = [123.csv, not.csv, 75839.csv, 2.csv, bad.csv, 23bad8.csv]''' and i would like to only work with [ 123.csv, 75839.csv, 2.csv]
i tried the following code:
'''for f in file_list:
if f.startwith('1' or '2' or '3' ..... or '9'):
#do somthing'''
but this does not some the problem if the file name starts with a number but still includes letters or other symboles later
thank you for your help!
CodePudding user response:
You can do it this way:
file_list = ["123.csv", "not.csv", "75839.csv", "2.csv", "bad.csv", "23bad8.csv"]
for f in file_list:
name, ext = f.rsplit(".", 1) # split at the rightmost dot
if name.isnumeric():
print(f)
Output is
123.csv
75839.csv
2.csv
CodePudding user response:
You can use Regex
to do the following:
import re
lst_of_files = ['temo1.csv', '12321.csv', '123123.csv', 'fdao123.csv', '12312asdv.csv', '123otk123.csv', '123.txt']
pattern = re.compile('^[0-9] .csv')
newlst = [re.findall(pattern, filename) for filename in lst_of_files if len(re.findall(pattern, filename)) > 0]
print(newlst)