I am working on a simple program to find the largest number in the file name in python, I have written a piece of code to print the file names from the directory.
import glob
for file_name in glob.iglob('src/*/*',recursive=True):
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions = final_string.split('.')
print(versions)
This is giving me names like this.
['V0', '0', '6']
['V0', '0', '7']
['V0', '0', '42']
['V0', '0', '35']
['V0', '0', '51']
['V0', '0', '1']
['V0', '0', '41']
['V0', '0', '38']
['V0', '0', '45']
Now I want to print the largest number from this. I am stuck here, suggestions are welcome.
CodePudding user response:
Something like the below
import glob
_max = None
for file_name in glob.iglob('src/*/*', recursive=True):
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions = final_string.split('.')
if _max is None:
_max = versions
else:
if int(_max[2]) < int(versions[2]):
_max = versions
print(_max)
CodePudding user response:
Just modified your code. It prints now the maximum number you have desired.
import glob
list_of_versions = []
for file_name in glob.iglob('src/*/*',recursive=True):
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions = final_string.split('.')
list_of_versions.append(versions)
largest_number = max(int(x[-1]) for x in list_of_versions)
print(largest_number)
CodePudding user response:
import glob
versions = []
for file_name in glob.iglob('src/*/*',recursive=True):
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions.append(final_string.split('.'))
max_ = 0
for l in versions:
if int(l[2]) > max_:
max_ = int(l[2])
print(f'Max is {max_}')
CodePudding user response:
Just added 2 lines in your code to get the max version number:
import glob
max_version = None
for file_name in glob.iglob('src/*/*',recursive=True):
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions = final_string.split('.')
print(versions)
if max_version and int(versions[-1]) > int(max_version):
max_version = versions[-1]
print (max_version)
CodePudding user response:
you search probably for something like
files_names = [
'a/b/V0.0.6__file.txt'
, 'a/b/V0.0.7__file.txt'
, 'a/b/V0.0.42__file.txt'
, 'a/b/V0.0.35__file.txt'
, 'a/b/V0.0.51__file.txt'
, 'a/b/V1.0.1__file.txt'
, 'a/b/V0.0.41__file.txt'
, 'a/b/V0.0.38__file.txt'
, 'a/b/V0.1.45__file.txt'
]
max0 = 0
max1 = 0
max2 = 0
res = 'not found'
for file_name in files_names:
file_result = file_name.split('/')[2]
final_string = file_result.split('__')[0]
versions = final_string.split('.')
ver0 = int(versions[0][1:]);
ver1 = int(versions[1]);
ver2 = int(versions[2]);
if (ver0 > max0) | ((ver0 == max0) & (ver1 > max1)) | ((ver0 == max0) & (ver1 == max1) & (ver2 > max2)):
max0 = ver0
max1 = ver1
max2 = ver2
res = file_name
print(res)