mercredi 6 juillet 2016

Recursive file renaming in python


I'm trying to write some code to recursively renaming files in python. I've got a root folder which has another folder inside it, and yet another folder inside that folder. Each of this folders has a file named "Name.txt" and I would like to change them to "Test.txt", in order to understand how os.walk() and os.rename() work. I've written this code:

# -*- coding: utf-8 -*-

import os


def renamefiles(path):

    rootstructure=os.walk(path,topdown=False)
    for root,dirs,files in os.walk(rootstructure):

        for filenames in files:

        fullfilename=os.path.abspath(filenames)

        os.rename(fullfilename,"Test.txt")



renamefiles(".")

However, I get this error:

File "/usr/lib/python2.7/os.py", line 278, in walk
names = listdir(top)
TypeError: coercing to Unicode: need string or buffer, generator found

What am I doing wrong?

Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire