文件夹下有很多个Excel工作表,都是以“Practice_数字”来命名的,现在想用一段程序自动修改工作表名称,但运行出现错误。
```python
import os
file_path = 'C:\\Users\\yxxxx5\\Desktop\\Learning'
file_list = os.listdir(file_path)
for i in file_list:
if i.startswith('~$'):
continue
new_name = i.replace('Practice', '练习')
old_file_path = os.path.join(file_path, i)
new_file_path = os.path.join(file_path, new_name)
os.rename(old_file_path, new_file_path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\yxxxx5\Desktop\Learning\Python' -> 'C:\Users\yxxxx5\Desktop\Learning\Python'
os.listdir(file_path) 获取的包含文件名和子目录名
C:\Users\yxxxx5\Desktop\Learning\Python是目录,目录不需要改名
要用 if os.path.isfile(old_file_path):判断下是不是文件
并且文件名中不包含'Practice'的也不需要改名, 不然
os.rename(old_file_path, new_file_path)
新文件名new_file_path与原文件名old_file_path一样就会出错
import os
file_path = 'C:\\Users\\yxxxx5\\Desktop\\Learning'
file_list = os.listdir(file_path)
for i in file_list:
old_file_path = os.path.join(file_path, i)
if os.path.isfile(old_file_path):
if i.startswith('~$') or 'Practice' not in i:
continue
new_name = i.replace('Practice', '练习')
new_file_path = os.path.join(file_path, new_name)
os.rename(old_file_path, new_file_path)
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
excel全部关闭再运行