-->

How to rename files using os.walk()?

2019-03-04 14:13发布

问题:

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