文件批量操作之旅
#文件重命名 os.rename("a.txt","b.txt")
#文件批量操作/my_code/test/1.jpg 2.jpg ...
import os
file_list=os.listdir("test/")#当前目录下的文件列表 相对路径:以当当前目录为起点的路径
for f in file_list:
print(f)
dest_file="re"+f
#f为原始文件名的名字,他不在工作目录(my_code),所以不能作为相对路径
#f文件的相对路径为test/f,或者直接写绝对路径
os.rename("test/"+f,"test/"+dest_file)
#采用绝对路径写代码 不允许写死
parent_dir=os.path.abspath("test")#获得父目录的绝对路径 即动态获取文件的绝对路径
#文件的绝对路径=父目录的绝对路径+文件名
source_file=os.path.join(parent_dir,f)#os.path.join 将目录和文件名连接起来
dest_file=os.path.join(parent_dir,dest_file)
os.rename(source_file,dest_file)
print(dest_file)
页:
[1]