简体   繁体   中英

python os.rename(…) won't work !

I am writing a Python function to change the extension of a list of files into another extension, like txt into rar, that's just an idle example. But I'm getting an error. The code is:

import os
def dTask():
    #Get a file name list
    file_list = os.listdir('C:\Users\B\Desktop\sil\sil2')
    #Change the extensions
    for file_name in file_list:
        entry_pos = 0;
        #Filter the file name first for '.'
        for position in range(0, len(file_name)):
            if file_name[position] == '.':
                break
        new_file_name = file_name[0:position]
        #Filtering done !
        #Using the name filtered, add extension to that name
        new_file_name = new_file_name + '.rar'
        #rename the entry in the file list, using new file name
        print 'Expected change from: ', file_list[entry_pos]
        print 'into File name: ', new_file_name
        os.rename(file_list[entry_pos], new_file_name)
        ++entry_pos
Error:
>>> dTask()
Expected change from:  New Text Document (2).txt
into File name:  New Text Document (2).rar
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    dTask()
  File "C:\Users\B\Desktop\dTask.py", line 19, in dTask
    os.rename(file_list[entry_pos], new_file_name)
WindowsError: [Error 2] The system cannot find the file specified

I can succeed in getting the file name with another extension in variable level as you can see in the print-out, but not in reality because I can not end this process in OS level. The error is coming from os.rename(...). Any idea how to fix this ?

  1. As the others have already stated, you either need to provide the path to those files or switch the current working directory so the os can find the files.

  2. ++entry_pos doesn't do anything. There is no increment operator in Python. Prefix + is just there fore symmetry with prefix - . Prefixing something with two + is just two no-ops. So you're not actually doing anything (and after you change it to entry_pos += 1 , you're still resetting it to zero in each iteration.

  3. Also, your code is very inelegant - for example, you are using a separate index to file_list and fail to keep that in synch with the iteration variable file_name , even though you could just use that one! To show how this can be done better.

-

def rename_by_ext(to_ext, path):
    if to_ext[0] != '.':
        to_ext = '.'+to_ext
    print "Renaming files in", path
    for file_name in os.listdir(path):
        root, ext = os.path.splitext(file_name)
        print "Renaming", file_name, "to", root+ext
        os.rename(os.path.join(path, file_name), os.path.join(path, root+to_ext))
rename_by_ext('.rar', '...')

os.rename really doesn't like variables. Use shutil. Example taken from How to copy and move files with Shutil .

import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
    if files.endswith(".txt"):
        shutil.move(files,destination)

In your case:

import shutil
shutil.move(file_list[entry_pos], new_file_name)

You also want to double backslashes to escape them in Python strings, so instead of

file_list = os.listdir('C:\Users\B\Desktop\sil\sil2')

you want

file_list = os.listdir('C:\\Users\\B\\Desktop\\sil\\sil2')

Or use forward slashes - Python magically treats them as path separators on Windows.

You must use the full path for the rename.

import os
def dTask():
    #Get a file name list
    dir = 'C:\Users\B\Desktop\sil\sil2'
    file_list = os.listdir(dir)
    #Change the extensions
    for file_name in file_list:
        entry_pos = 0;
        #Filter the file name first for '.'
        for position in range(0, len(file_name)):
            if file_name[position] == '.':
                break
        new_file_name = file_name[0:position]
        #Filtering done !
        #Using the name filtered, add extension to that name
        new_file_name = new_file_name + '.rar'
        #rename the entry in the file list, using new file name
        print 'Expected change from: ', file_list[entry_pos]
        print 'into File name: ', new_file_name
        os.rename( os.path.join(dir, file_list[entry_pos]), os.path.join(dir,new_file_name))
        ++entry_pos

如果您不在目录C:\\Users\\B\\Desktop\\sil\\sil2 ,那么Python当然将找不到这些文件。

import os

def extChange(path,newExt,oldExt=""):
    if path.endswith != "\\" and path.endswith != "/":
        myPath = path + "\\"
    directory = os.listdir(myPath)
    for i in directory:
        x = myPath + i[:-4] + "." + newExt
        y = myPath + i
        if oldExt == "":
            os.rename(y,x)
        else:
            if i[-4:] == "." + oldExt:
                os.rename(y,x)

now call it:

extChange("C:/testfolder/","txt","lua") #this will change all .txt files in C:/testfolder to .lua files
extChange("C:/testfolder/","txt") #leaving the last parameter out will change all files in C:/testfolder to .txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM