Reputation: 35
How can I list all file of a directory in Python and remove them by .log?
for root, dirs, files in os.walk(r'/home/m110/public_html/ts/'):
print(files)
output1281.log
output1020.log
log3.log
mem.py
output1087.log
bunker3.py
output1248.log
output1311.log
output1099.log
output1261.log
output1282.log
output1213.log
log43.log
output1291.log
output1095.log
output1209.log
usr.txt
output1210.log
log7.log
output1042.log
attack.py
output1032.log
output1318.log
i run this code in Centos7 but i just need list file with .log file extension for delete times
Upvotes: 0
Views: 995
Reputation: 1130
import os
import shutil
files= next(os.walk(r'/home/m110/public_html/ts/'))[2]
for filename in files:
ex=filename.split(".")[-1]
if ex=='log':
#print ex
os.remove(filename)
Upvotes: 0
Reputation: 3862
If you want to use os
:
for root, dirs, files in os.walk('/home/m110/public_html/ts/'):
for file in files:
if file.endswith('.log'):
os.remove(root + '/' + file)
In Python 3+, you can use pathlib
:
paths = pathlib.Path('/home/m110/public_html/ts/').glob('*.log')
for path in paths:
path.unlink()
Upvotes: 1
Reputation: 678
This could be accomplished by calling rm *.log
in the bash as well, but for python:
import os
from glob import glob
log_file_list = glob('folder/*.log')
for file in log_file_list:
os.remove(file)
This is only works for files in the top level of a folder.
Glob does pathname pattern matching as the unix bash does, os.remove
removes a file with a given path.
If you want to include subfolders, you can set the recursive=True
flag and change the search expression like so:
import os
from glob import glob
log_file_list = glob('folder/**/*.log', recursive=True)
for file in log_file_list:
os.remove(file)
Upvotes: 0