开发者

how to remove a variable in conjunction of functions in the loop?

def wpath():
    defpath = '/home/me/documents/'
    os.chdir(defpath)
    path = str(input("would you like to change current working directory? [y/yes] if you want"))
    if path == 'yes' or path == 'y':
        while True:
            try:
                os.chdir(input('Enter new path! \n'))
                break
            except OSError:
                print('\nno such directory! Try again!')
    else:
        pass
    src()


开发者_开发问答def src():
    global d
    d = {}
    n = 0
    for file in os.listdir('.'):
        if re.search('.?\.(txt|csv|log)', file):
            n += 1
            print(n, file)
            d[n] = file
    if len(d) == 0:
        del d
        wpath()

wpath()

val = int(input('Enter number of file\n'))
if val in d:
    source = d[val]

After I published my post, I realized my mistake. Thanks. Now the code works. I've corrected the code in my question.


You invoke del d only if len(d) == 0. Does that happen? Can you insert a print call into that branch and see if del is actually called?

That said, del d is a code smell. I'm 99.99% sure you don't really need to use it here. Can you explain what it is you're trying to do exactly?

Besides that, why do you need d as a dictionary, if you only add consecutive numeric keys to it? Would it not be better to have a list and append to it instead?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜