Reputation: 87
I am trying to create a function that would listdir into a list, then iterate over the list and remove the last 3 elements. I have used this code before but I am getting an odd error, please see the log below. I have research the error that I am catching with AttributeError and my results have been null. Can anyone please shed some light on what I may be overlooking? Please let me know if you need more information. Thank you.
[root@dbadmin bin]# python --version
Python 2.6.6
[root@dbadmin bin]# uname -a
Linux dbadmin 2.6.32-504.8.1.el6.x86_64 #1 SMP Wed Jan 28 21:11:36 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
FUNCTION:
def clean_up():
dir_list = os.listdir('/root/repo_creation/repos')
srtd_lst = sorted(dir_list)
dirs_to_remove = srtd_lst[:-3]
for dirs in dirs_to_remove:
try:
logger.info("Removing dir: %s" % dirs)
print os.path.join(dir_list, dirs)
except AttributeError as e:
logger.info(e)
[root@dbadmin bin]# ls -l /root/repo_creation/repos/
total 24
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-03
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-04
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-05
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-06
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-07
drwxr-xr-x 2 root root 4096 Jun 4 23:50 2016-08
LOG_OUTPUT:
[root@dbadmin bin]# python repo_creator.py
[root@dbadmin bin]# cat ../log/std_out.2016-06-07.log
2016-06-07 09:12:12,152 - __main__ - INFO - Removing dir: 2016-03
2016-06-07 09:12:12,152 - __main__ - INFO - 'list' object has no attribute 'endswith'
2016-06-07 09:12:12,152 - __main__ - INFO - Removing dir: 2016-04
2016-06-07 09:12:12,152 - __main__ - INFO - 'list' object has no attribute 'endswith'
2016-06-07 09:12:12,152 - __main__ - INFO - Removing dir: 2016-05
2016-06-07 09:12:12,153 - __main__ - INFO - 'list' object has no attribute 'endswith'
Upvotes: 0
Views: 2649
Reputation: 76254
print os.path.join(dir_list, dirs)
dir_list
is a list, but os.path.join
's arguments need to be individual strings.
It's not clear to me what you're trying to do here. If you just want to display dirs
, you don't need join
at all. Just print it by itself.
print dirs
edit: if you want dirs
to be prefixed with the relative path you used in listdir
, join it with that rather than the result of listdir
.
root_directory = '/root/repo_creation/repos'
dir_list = os.listdir(root_directory)
#... Later in the code...
print os.path.join(root_directory, dirs)
Upvotes: 1