My question is : How to sort files by name and delete in Python.

What i want and mean is:
In TextFolder have:
a1.txt
a2.txt
a3.txt
a4.txt
a5.txt
a6.txt
a7.txt
a8.txt
a9.txt
a10.txt
i wan sort the file by name and
i only wan keep 10 files only in the folder. So...
when a11.txt available, then it will delete a1.txt.
when a12.txt available, then it will delete a2.txt.

Hope you guys can help me out in this, thx.

Be aware that sorting strings will not necessarily behave as you would expect:

myfiles = [
'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt', 'a5.txt',
'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt', 'a10.txt', 'a11.txt'
]

print(myfiles)
print('-'*60)

myfiles_sorted = sorted(myfiles)
print(myfiles_sorted)

"""my result -->
['a1.txt', 'a2.txt', 'a3.txt', 'a4.txt', 'a5.txt', 
'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt', 'a10.txt', 'a11.txt']
------------------------------------------------------------
['a1.txt', 'a10.txt', 'a11.txt', 'a2.txt', 'a3.txt', 
'a4.txt', 'a5.txt', 'a6.txt', 'a7.txt', 'a8.txt', 'a9.txt']
"""

For this to work you would have to name your files something like a02.txt and a12.txt

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.