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

2024-06-11 08:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个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

我可以成功地在变量级别获得另一个扩展名为的文件名,正如您在打印输出中看到的那样,但实际上不是这样,因为我不能在操作系统级别结束此过程。错误来自os.rename(…)。知道怎么解决吗?


Tags: thenameinposnewforosposition
3条回答

rename确实不喜欢变量。使用shuil。取自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)

就你而言:

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

您还希望使用双反斜杠以在Python字符串中转义它们,因此

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

你想要的

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

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

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

  2. ++entry_pos什么都不做。Python中没有increment运算符。前缀+与前缀-正对称。在某物前面加上两个+只是两个no ops。所以你实际上什么也没做(在你把它改成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', '...')

相关问题 更多 >