How to sort multiple FASTA files based on their content?
The general idea is:

iterate over all files

read the first line of each file, extract the segment bit
move the file based on that



In Python, this can be done in many ways. Here’s one way:
import os
import re


def find_segment(id):
    return re.search(r'segment (\d)', id).group(1)


for segment in range(8):
    os.mkdir(f'segment-{segment + 1}')

for entry in os.scandir():
    if not entry.is_file():
        continue

    with open(entry.path, 'r') as file:
        segment = find_segment(next(file))
    os.rename(entry.path, f'segment-{segment}/{entry.path}')

Note the absence of error handling — this code assumes that every operation succeeds; empty files, or files without “segment X” in their FASTA ID, will trigger an error, as will the usual IO failures (missing permissions, etc.).

But most people would probably use a shell scripting language instead of Python to solve this. For example, here’s something equivalent in Bash (untested):
mkdir segment-{1..8}

for file in *.fa *.fasta; do
    segment=$(sed 's/.*segment \([[:digit:]]\).*/\1/; q' "$file&quot;)
    if [[ -n $segment ]]; then
    mv "$file&quot; &quot;segment-$segment&quot;
    done
done