質問

I have a large directory structure, each directory containing multiple sub-directories, multiple .mbox files, or both. I need to rename all the .mbox files to the respective file name without the extension e.g. bar.mbox -> bar foo.mbox -> foo

Here is the script I've written:

# !/usr/bin/python
import os, sys

def walktree(top, callback):
    for path, dirs, files in os.walk(top):
        for filename in files:
            fullPath = os.path.join(path, filename)
            callback(fullPath)

def renameFile(file):
    if file.endswith('.mbox'):
        fileName, fileExt = os.path.splitext(file)
        print file, "->", fileName
        os.rename(file,fileName)

if __name__ == '__main__':
    walktree(sys.argv[1], renameFile)

When I run this using:

python walktrough.py "directory"

I get the error:

Traceback (most recent call last):
  File "./walkthrough.py", line 18, in <module>
    walktree(sys.argv[1], renameFile)
  File "./walkthrough.py", line 9, in walktree
    callback(fullPath)
  File "./walkthrough.py", line 15, in renameFile
    os.rename(file,fileName)
OSError: [Errno 21] Is a directory
役に立ちましたか?

解決

This was solved by adding an extra conditional statement to test if the name the file was to be changed to, was a current directory.

If this was true, the filename to-be had an underscore added to.

Thanks to WKPlus for the hint on this.

BCvery1

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top