[英]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. 我正在编写一个Python函数,将文件列表的扩展名更改为另一个扩展名,例如将txt更改为rar,这只是一个空闲示例。 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. 如打印输出所示,我可以成功获得可变级别的另一个扩展名的文件名,但实际上却无法实现,因为我无法在OS级别结束此过程。 The error is coming from os.rename(...).
错误来自os.rename(...)。 Any idea how to fix this ?
任何想法如何解决这个问题?
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. 正如其他人已经指出的那样,您要么需要提供这些文件的路径,要么切换当前的工作目录,以便操作系统可以找到这些文件。
++entry_pos
doesn't do anything. ++entry_pos
不执行任何操作。 There is no increment operator in Python. 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. 因此,您实际上并没有执行任何操作(将其更改为
entry_pos += 1
,您仍会在每次迭代中将其重置为零。
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! 另外,您的代码非常笨拙-例如,您正在对
file_list
使用一个单独的索引,即使您只能使用该索引,也无法使其与迭代变量file_name
保持同步! 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. os.rename确实不喜欢变量。 Use shutil.
使用shutil。 Example taken from How to copy and move files with Shutil .
摘自如何使用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 您还希望将反斜杠加倍以在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上神奇地将它们视为路径分隔符。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.