
刚接触python,写了一段简单的代码,功能就是重命名一个文件,代码如下:
1 2 3 4 5 6 7 | list_1=os.listdir( "." )
for files in list_1:
f=open(files)
if f.name== "01.txt" :
os.rename( '01.txt' , '001.txt' )
elif f.name== "05.txt" :
os.rename( "05.txt" , "005.txt" )
|
相关推荐:《Python教程》
这么简单几行代码确报错了:
1 2 3 4 | Traceback (most recent call last):
File "E:\workspace\pytest01\src\filetest\RaedFileMethord.py" , line 96, in <module>
os.rename( '01.txt' , '001.txt' )
WindowsError: [Error 32]
|
百思不得其解,搜下才知道,原来:
Error 32是文件已经打开的错误,我忘记在改名前关闭文件了。
于是添加了两行代码,f.close()。
1 2 3 4 5 6 7 8 9 | list_1=os.listdir( "." )
for files in list_1:
f=open(files)
if f.name== "01.txt" :
f.close()
os.rename( '01.txt' , '001.txt' )
elif f.name== "05.txt" :
f.close()
os.rename( "05.txt" , "005.txt" )
|
嘿,成功了,又执行了一遍,结果又报错了,
1 2 3 4 | Traceback (most recent call last):
File "E:\workspace\pytest01\src\filetest\RaedFileMethord.py" , line 96, in <module>
os.rename( '01.txt' , '001.txt' )
WindowsError: [Error 183]
|
这个是因为文件已经存在造成的,重复执行的时候会报这个错误,删下文件,哈哈,没问题了。