关于搜索全部文件和修改文件名的方法os.walk() 和os.listdir

os.walk()遍历所有的文件并列出各级,os.listdir()只列出当前文件下的条目,一个列表

1.os.walk() 大材小用。

import os
path = 'j:\juypter\爬虫\百度图片\'
for dirnames, subnames, files in os.walk(path):#父目录,子目录,文件名称
    for file in files:#只取files里的文件名,不含目录
        new_name = '美女' + file
        os.rename(path + file, path + new_name)#重命名,写入相同的文件。

2,listdir()

import os
path = 'j:\juypter\爬虫\风景图\'
for file in os.listdir(path):    #os.listdir('.')遍历文件夹内的每个文件名,并返回一个包含文件名的list
    new_name = '风景图' + file[6:]
    os.rename(path + file, path + new_name)
原文地址:https://www.cnblogs.com/Zhu-Xueming/p/8387514.html