python os.rename(...) 不起作用!

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4147438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:27:37  来源:igfitidea点击:

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

pythonfile-rename

提问by Mr ME

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:

我正在编写一个 Python 函数来将文件列表的扩展名更改为另一个扩展名,例如将 txt 更改为 rar,这只是一个闲置示例。但我收到一个错误。代码是:

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 ?

正如您在打印输出中看到的那样,我可以成功地在变量级别获取带有另一个扩展名的文件名,但实际上并非如此,因为我无法在操作系统级别结束此过程。错误来自 os.rename(...)。知道如何解决这个问题吗?

回答by Rod

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

回答by chrisaycock

If you aren't in the directory C:\Users\B\Desktop\sil\sil2, then Python certainly won't be able to find those files.

如果您不在目录中C:\Users\B\Desktop\sil\sil2,那么 Python 肯定无法找到这些文件。

回答by chrisaycock

  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_posdoesn'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_listand 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.

  1. 正如其他人已经说过的,您需要提供这些文件的路径或切换当前工作目录,以便操作系统可以找到这些文件。

  2. ++entry_pos什么都不做。Python 中没有增量运算符。Prefix+只是为了与 prefix 对称-。用两个前缀+只是两个无操作。因此,您实际上并没有做任何事情(并且在将其更改为 之后entry_pos += 1,您仍然在每次迭代中将其重置为零。

  3. 此外,您的代码非常不优雅——例如,您使用了一个单独的索引,file_list并且未能与迭代变量保持同步file_name,即使您可以只使用那个!展示如何更好地做到这一点。

-

——

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', '...')

回答by Russell Borogove

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

您还想加倍反斜杠以在 Python 字符串中对它们进行转义,而不是

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.

或者使用正斜杠 - Python 神奇地将它们视为 Windows 上的路径分隔符。

回答by Mahi

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

回答by brddawg

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

os.rename 真的不喜欢变量。使用吸尘器。示例取自How to copy and move files with Shuutil

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)