[Tutor] conditional renaming folder and files in the tree

Peter Otten __peter__ at web.de
Mon Aug 14 12:47:36 EDT 2017


banda gunda wrote:

> Dear Tutor,
> 
> 
> I have made some progress!
> 
> But not yet got the results.
> 
> Attached is revised code.
> 
> 
> Specifically, the problem in below:
> 
> 
> for root, dirs, files in os.walk(".", topdown=False):
>     for name in files:
>         print(os.path.join(root, name))
>         os.rename(path + name, path + name.replace("---", "changed"))

The `path` variable appears out of the blue here -- it should probably be 
`root`. Also, you should make it a habit to use os.path.join() to construct 
filenames, not string concatenation. The reason is that os.path.join() knows 
when to insert a path separator, and will pick the right one for the 
platform the script is running on.

>         #os.rename(path + "\\"+ name, path + "\\"+ name.replace("---",
>         #"changed")

Do us (and yourself!) a favour, and remove abandoned code like the line 
above. It only makes the code harder to follow, and the one who suffers most 
from that are you. If you are afraid that you will lose valuable snippets 
put them elsewhere or consider adopting a version control system which 
allows you to go back to a former version when you find that a change was 
unsuccessful.

>         files[name] = os.sep.join([dirpath, name])

That doesn't make sense. What are you trying to achieve here?

> 
>         print (files)
> 
>     for name in dirs:
>         print(os.path.join(root, name))
> 
> 
> .\---DAT1\---DAT3\---000010.txt

Note that os.rename() can make a mess of your data. I recommend that you use 
print statements instead until you are sure that your script does what you 
want, something like

def dryrun_rename(old, new):
    print("rename", old)
    print("to    ", new)
    print()

for parent_dir, dirs, files in os.walk(".", topdown=False):
    for name in files:
        old_path = ... # construct filepath from parent_dir and name 
        new_path = ... # construct filepath from parent_dir and modified
                       # name
                       # use os.path.join in both cases
        dryrun_rename(old_path, new_path)

Once this prints what you expect you can swap dryrun_rename for os.rename.



More information about the Tutor mailing list