开发者

why my os.listdir return the same folder?

sory, if my english bad...

i'm trying to get a list of my dir this way:

import os, os.path  

_path = "/opt开发者_高级运维/local"#this because i use mac
_dir_path = os.listdir(_path)
_tmp_attr = {"name":"","type":""}
_tmp_data =[]

for _dir_name in _dir_path:
   _tmp_attr["name"] = _dir_name
   if os.path.isdir(_path+'/'+_dir_name):
     _tmp_attr["type"] = "Dictionary"
   _tmp_data.append(_tmp_attr)
print _tmp_data  

but it print only the last directory

[{'type': 'Dictionary', 'name': 'www'}, {'type': 'Dictionary', 'name': 'www'}, ... ]


You're re-using the same "_tmp_attr" dictionary in every loop iteration, so you're just re-adding the same instance to the _tmp_data collection and overwriting its contents in every iteration.

You need to initialize a new dictionary in every iteration:

_tmp_attr = { }


What you have here is an object referencing issue. The _tmp_attr you are adding to the list are infact the same object. Each iteration of the loop simply updates it. You need to create a new _tmp_attr object for each iteration in-order for the list elements to be unique. When the loop falls through you are simply left with multiple references in the list to the same object. doing this in the loop may help:

type = ""
if os.path.isdir(os.path.join(_path,_dir_name)):
    type = "Dictionary"
_tmp_data.append({"type":type,"name":_dir_name})


you may also want to look at os.walk

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜