在下面的代码中,为什么我必须将num
变量设置为函数内的global
,而不是folder
或rename_prefix
?如果我从函数中移除global
,则num
无法在函数中使用,但folder
和rename_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
答案 0 :(得分:2)
正如评论中的人指出的那样,您不需要global
用于folder
和rename_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