0

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.

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by sneekula
0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.