修改任意目录下文件名字python
path_dir = r'目录地址' # 获取目录下的全部文件 a = os.listdir(path_dir) n = 0 for i in a: n += 1 x = str(n) # 分割路径,返回路径名和文件扩展名的元组 ext = os.path.splitext(i) # 只修改后缀为.txt的文件 if ext[1] == '.txt' # 修改后的名字 new_name = x + ext[1] # 要修改的路径下的文件 oldfile = os.path.join(path_dir, i) # 修改后名字的路径 newfile = os.path.join(path_dir, new_name) # 重命名 os.rename(oldfile, newfile)
修改当前目录下文件名字code
# 当前目录 path_dir = os.getcwd() # 获取目录下的全部文件 a = os.listdir() n = 0 for i in a: n += 1 x = str(n) # 分割路径,返回路径名和文件扩展名的元组 ext = os.path.splitext(i) # 只修改后缀为.txt的文件 if ext[1] == '.txt': # 修改后的名字 new_name = x + ext[1] # 要修改的路径下的文件 oldfile = os.path.join(path_dir, i) # 修改后名字的路径 newfile = os.path.join(path_dir, new_name) # 重命名 os.rename(oldfile, newfile)