How to rename files using os.walk()?

*爱你&永不变心* 提交于 2019-12-02 07:57:50

You have to pass the full path of the file to os.rename. First item of the tuple returned by os.walk is the current path so just use os.path.join to combine it with file name:

import os

for path, dirs, files in os.walk("./data"):
    for file in files:
        pieces = list(os.path.splitext(file))
        pieces[0] = pieces[0][:-4]
        newFile = "".join(pieces)
        os.rename(os.path.join(path, file), os.path.join(path, newFile))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!