为什么有些变量需要全局变量而其他变量不需要?

时间:2016-08-12 17:19:35

标签: python global-variables

在下面的代码中,为什么我必须将num变量设置为函数内的global,而不是folderrename_prefix?如果我从函数中移除global,则num无法在函数中使用,但folderrename_prefix变量仍可以使用?我不明白。有人可以解释我对全球和地方变量的误解。谢谢

import os

# User Input
folder = r'F:\Pictures\2016\iPhone Pics\rename_test'
rename_prefix = 'Renamed_' # ENTER WHAT YOU WANT PREFIX OF IMAGE TO BE
num = 0

def file_renamer():
    global num
    for root, dir2, files in os.walk(folder):
        print 'Renaming Files in {} \n'.format(root)
        if len(dir2) > 0:
            print 'Found the following sub folders {} \n'.format(dir2)
        #print 'Found {} subfolders named {} and {}'.format(len(dir2),dir2[0],dir2[1])
        #num = 0 uncomment if you want each folder to start renaming files at 0
        for x in files:
            local_folder = os.path.join(folder, root)
            old = os.path.join(local_folder, x)
            #if x.startswith('IMG'):

            if old.lower().endswith(('.jpg')):

                print 'Renaming {0}'.format(x)
                num2 = '{0}.jpg'.format(num)
                rename_name = rename_prefix + num2
                rename_path = os.path.join(local_folder, rename_prefix + num2)
                os.rename(old, rename_path)
                print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
                num += 1
            elif old.lower().endswith('.png'):
                print 'Renaming {0}'.format(x)
                num2 = '{0}.png'.format(num)
                rename_name = rename_prefix + num2
                rename_path = os.path.join(local_folder, rename_prefix + num2)
                os.rename(old, rename_path)
                print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
                num += 1

            elif old.lower().endswith('.mov'):
                print 'Renaming {0}'.format(x)
                num2 = '{0}.mov'.format(num)
                rename_name = rename_prefix + num2
                rename_path = os.path.join(local_folder, rename_prefix + num2)
                os.rename(old, rename_path)
                print 'Successfully renamed {0} to {1} \n'.format(x, rename_name)
                num += 1

            else:
                print 'IDK what file type {0} is !!, skipping...'.format(x)
                continue
            #else:
                #print '{} Does not meet renaming criteria, moving to next file'.format(x)
                #continue

    print 'Finished Renaming all files in {}'.format(folder)


file_renamer()enter code here

2 个答案:

答案 0 :(得分:2)

正如评论中的人指出的那样,您不需要global用于folderrename_prefix,而是用于num的原因是您在你设定后者的时候,只会阅读前两个。

如果你没有宣布num全局,那么会发生num的分配会创建并分配给新的局部变量num,这将影响全局{{1}而不是像你期望的那样实际设置已经定义的全局num的值。

答案 1 :(得分:1)

x = 0

def function_name():
    x = 2


function_name()

x #yields:0

但如果你定义:

def function_name():
    global x
    x = 2

然后执行

function_name()
x #yields 2