0

I have written a Python script to rename all files in a folder. The code is:

import os
import sys
import platform

walk_dir = dir_path = os.path.dirname(os.path.realpath(__file__))

print('walk_dir = ' + walk_dir)
print('walk_dir (absolute) = ' + os.path.abspath(walk_dir))

filePathList =[]
for root, subdirs, files in os.walk(walk_dir):
    for filename in files:
        file_path = os.path.join(root, filename)
        filePathList.append(file_path)

total =  len(filePathList)

print str(total) + " files found.\n\n\n"

count = 0
for file in filePathList:
    count = count + 1
    if file == os.path.realpath(__file__):
        continue
    old_file_name = file
    parentDirectories = str(file).split('/')
    dir_lenght = len(parentDirectories)
    new_file_name = ''
    index = 0
    while index < dir_lenght - 1:
        new_file_name = new_file_name + parentDirectories[index] + '/'
        index = index + 1
    new_file_name = new_file_name + parentDirectories[dir_lenght -2] + '_' + parentDirectories[dir_lenght - 1]

    os.rename(old_file_name, new_file_name)

This works fine on ubuntu OS but in windows it gives error. Error occurs in last line 'os.rename(old_file_name, new_file_name)'. The error message is :

 Traceback (most recent call last):  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 1531, in     globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.1.4\helpers\pydev\pydevd.py", line 938, in run    pydev_imports.execfile(file, globals, locals)  # execute the script
File "E:/Music/Bangla - Copy/reursiveFileRenameAppendFolderName.py", line 67, in     os.rename(old_file_name, new_file_name)
WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

Why this script is behaving differently in different operating system? How to make this script work in Windows OS, too?

martineau
  • 119,623
  • 25
  • 170
  • 301
naimul64
  • 133
  • 3
  • 17
  • 3
    Why this script is behaving differently in different operating system? Because you're manually constructing your filesystem paths, and that works differently (\ vs /) in different OSs. Try using `os.path.join` to generate the path. https://docs.python.org/2/library/os.path.html#os.path.join – ChidG Mar 14 '17 at 05:39
  • Have you tried printing the new filename before trying it? As the comment above says, it might be related to the way you're manually constructing these paths. – TigerhawkT3 Mar 14 '17 at 05:39
  • Thanks a lot. It worked. – naimul64 Mar 19 '17 at 11:16

0 Answers0