How to rename files using os.walk()?

一笑奈何 提交于 2019-12-04 06:24:11

问题


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 files in one directory using:

import glob, os

for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
    pieces = list(os.path.splitext(file))
    pieces[0] = pieces[0][:-4]
    newFile = "".join(pieces)       
    os.rename(file,newFile)

But now I want to repeat the above in all subdirectories. I tried using os.walk():

import os

for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
    for file in files:
        pieces = list(os.path.splitext(file))
        pieces[0] = pieces[0][:-4]
        newFile = "".join(pieces)       
        # print "Original filename: " + file, " || New filename: " + newFile
        os.rename(file,newFile)

The print statement correctly prints the original and the new filenames that I am looking for but os.rename(file,newFile) returns the following error:

Traceback (most recent call last):
  File "<input>", line 7, in <module>
WindowsError: [Error 2] The system cannot find the file specified

How could I resolve this?


回答1:


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))


来源:https://stackoverflow.com/questions/41061291/how-to-rename-files-using-os-walk

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!