Python Forum
Read directory listing of files and parse out the highest number?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Read directory listing of files and parse out the highest number?
#6
Another approach:
test conditions:
directory in same path as script, named 'filedir' (you can change as needed)
containing the following files:
Output:
igMess_9.csv igMess_10.csv igMess_11_.csv igMess_12_.csv igMess_13_.csv
from pathlib import Path
import os


os.chdir(os.path.abspath(os.path.dirname(__file__)))

def check_for_highest(StartsWith, EndsWith, Directory):
    dir = Path(Directory)
    filelist = [filename for filename in dir.iterdir() \
        if filename.is_file() and str(filename.stem).startswith(StartsWith) \
        and str(filename.stem).endswith(EndsWith)]
    largest_name = sorted(filelist)[-1]
    return filelist, largest_name

def testit():
    filelist, largest = check_for_highest('igMess_', '_', 'filedir')

    for file in filelist:
        print(file)

    next_available = str(int(largest.stem[7:-1]) + 1)
    print(f"next available number = {next_available}")

testit()
results:
Output:
filedir/igMess_11_.csv filedir/igMess_12_.csv filedir/igMess_13_.csv next available number = 14
Reply


Messages In This Thread
RE: Read directory listing of files and parse out the highest number? - by Larz60+ - Sep-28-2022, 10:15 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Filer and sort files by modification time in a directory tester_V 5 402 May-02-2024, 05:39 PM
Last Post: tester_V
  Loop through all files in a directory? Winfried 10 611 Apr-23-2024, 07:38 PM
Last Post: FortuneCoins
  uploading files from a ubuntu local directory to Minio storage container dchilambo 0 528 Dec-22-2023, 07:17 AM
Last Post: dchilambo
  change directory of save of python files akbarza 3 1,003 Jul-23-2023, 08:30 AM
Last Post: Gribouillis
  Using pyinstaller with .ui GUI files - No such file or directory error diver999 3 3,672 Jun-27-2023, 01:17 PM
Last Post: diver999
  parse/read from file seperated by dots giovanne 5 1,177 Jun-26-2023, 12:26 PM
Last Post: DeaD_EyE
  Monitoring a Directory for new mkv and mp4 Files lastyle 3 1,720 May-07-2023, 12:33 PM
Last Post: deanhystad
  Listing directories (as a text file) kiwi99 1 880 Feb-17-2023, 12:58 PM
Last Post: Larz60+
  How to read in mulitple files efficiently garynewport 3 945 Jan-27-2023, 10:44 AM
Last Post: DeaD_EyE
  python read iperf log and parse throughput jacklee26 4 2,902 Aug-27-2022, 07:04 AM
Last Post: Yoriz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020