Search code examples
pythonoperating-systempython-3.6rename

Impossible to rename extension file


I am dealing with a list of file ending with this extension : .abstr.

My aim is to rename the files to txt format and extract text from those file and put it in dataframe.

for root, dirs, files in os.walk('spr_train_plain/'):
    for file in files:
        filename, extension = os.path.splitext(file)
        os.rename(file, filename + ".txt")
      

error


[WinError 2] Le fichier spécifié est introuvable: 'Art.001.eng.abstr' -> 'Art.001.eng.txt'

I do not understand why I get this error ?


Solution

  • os.walk docs states that

    (...)Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name)(...)

    so you should replace

    filename, extension = os.path.splitext(file)
    

    using

    filename, extension = os.path.splitext(os.path.join(root,file))