How to rename files using os.walk()?

后端 未结 1 1551
孤城傲影
孤城傲影 2021-01-26 11:41

I\'m trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use glob.glob() to locate and rename file

相关标签:
1条回答
  • 2021-01-26 12:25

    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))
    
    0 讨论(0)
提交回复
热议问题