|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
疑惑来自小甲鱼零基础学习python,第30讲课后作业,第3题
http://bbs.fishc.com/thread-45649-1-1.html
第3题参考答案如下:
import os
def search_file(start_dir, target) :
os.chdir(start_dir)
for each_file in os.listdir(os.curdir) :
ext = os.path.splitext(each_file)[1]
if ext in target :
vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) # 使用os.sep是程序更标准
if os.path.isdir(each_file) :
search_file(each_file, target) # 递归调用
os.chdir(os.pardir) # 递归调用后切记返回上一层目录
start_dir = input('请输入待查找的初始目录:')
program_dir = os.getcwd()
target = ['.mp4', '.avi', '.rmvb']
vedio_list = []
search_file(start_dir, target)
f = open(program_dir + os.sep + 'vedioList.txt', 'w')
f.writelines(vedio_list)
f.close()
-------------------------------------
请教下,vedio_list是函数外面定义的变量,为何可以在函数里面去修改(这里是append)呢?不是说函数里面要修改全局变量,需要先global么?
python中的变量分为可变变量和不可变变量,列表、字典等是可变变量,即修改其局部,其地址不变,就是说在原地址的值可变。
对于可变变量,在函数中修改其局部,是可以看成全局变量的,例如:
- >>> list1 = [1, 2]
- >>> def fun():
- list1.append(3)
-
- >>> fun()
- >>> list1
- [1, 2, 3]
复制代码
但如果是重新赋值,就会改变其地址,就相当于不可变变量了,不用global,则不会改变外层的变量。
- >>> list1 = [1, 2]
- >>> def fun():
- list1 = [4, 5, 6]
-
- >>> fun()
- >>> list1
- [1, 2]
复制代码
|
|