文件改名并移动

最近做完一个实验,但是是分期做的所以结果存在两个文件夹下面,我要给一个文件夹下的结果重新编号并复制到另一个存储结果的文件下

代码实现

import os
import shutil
#设置模型名称
model_name = "BilSTM"
def rename(path):
    '该文件夹下所有的文件(包括文件夹)'
    FileList = os.listdir(path)
    '遍历所有文件,files是字符串形式'
    for files in FileList:
        '原来的文件路径'
        oldDirPath = os.path.join(path, files)
        '如果是文件夹则递归调用'
        if os.path.isdir(oldDirPath):
            rename(oldDirPath)
        '文件名'
        fileName = os.path.splitext(files)[0]
        #如果文件开头是“1_”则将1替换为5
        if(fileName[0:2]=="1_"):
                fileName= "5" + fileName[1:]
        print(fileName)
        '文件扩展名'
        fileType = os.path.splitext(files)[1]
        print(fileType)
        '新的文件路径=老的路径加上新的文件名(新的文件名=修改后的名字加上后缀)'
        newDirPath = os.path.join(path, fileName + fileType)
        '重命名'
        os.rename(oldDirPath, newDirPath)
def movefile(path):
	FileList = os.listdir(".")
	#遍历统计所有的文件夹
	for files in FileList:
		#扩充待复制文件路径到文件夹
		old_path = os.path.join(".", files)
		#如果是文件夹则访问文件下的文件
		if os.path.isdir(old_path):
			#扩充待黏贴位置文件路径
			new_path = os.path.join(path, files)
			Files = os.listdir(old_path)
			for file in Files:
				#扩充待复制文件路径到文件
				file_path =  os.path.join(old_path, file)
				#复制文件到新的位置
				shutil.copy(file_path,new_path)
	
	
if __name__ == "__main__":
		#文件直接放在待改名和移动的结果同一个目录下
        path = '.'
        #对文件同级目录下的所有文件夹中的文件进行遍历和改名
        rename(path)
        #确定移动到的位置,返回当前文件的上级目录进入以模型命名的另一个存储的文件夹下
        station = "../"+model_name
        movefile(station)

知识总结

python 实现遍历文件夹下所有文件或文件夹重命名

os.listdir() 方法用于返回指定的文件夹包含的文件或文件夹的名字的列表。
os.path 模块主要用于获取文件的属性。
以下是 os.path 模块的几种常用方法:
方法 说明
os.path.abspath(path) 返回绝对路径
os.path.basename(path) 返回文件名
os.path.commonprefix(list) 返回list(多个路径)中,所有path共有的最长的路径
os.path.dirname(path) 返回文件路径
os.path.exists(path) 如果路径 path 存在,返回 True;如果路径 path 不存在,返回 False。
os.path.lexists 路径存在则返回True,路径损坏也返回True
os.path.expanduser(path) 把path中包含的""和"user"转换成用户目录
os.path.expandvars(path) 根据环境变量的值替换path中包含的" n a m e " 和 " name"和" name""{name}"
os.path.getatime(path) 返回最近访问时间(浮点型秒数)
os.path.getmtime(path) 返回最近文件修改时间
os.path.getctime(path) 返回文件 path 创建时间
os.path.getsize(path) 返回文件大小,如果文件不存在就返回错误
os.path.isabs(path) 判断是否为绝对路径
os.path.isfile(path) 判断路径是否为文件
os.path.isdir(path) 判断路径是否为目录
os.path.islink(path) 判断路径是否为链接
os.path.ismount(path) 判断路径是否为挂载点
os.path.join(path1[, path2[, …]]) 把目录和文件名合成一个路径
os.path.normcase(path) 转换path的大小写和斜杠
os.path.normpath(path) 规范path字符串形式
os.path.realpath(path) 返回path的真实路径
os.path.relpath(path[, start]) 从start开始计算相对路径
os.path.samefile(path1, path2) 判断目录或文件是否相同
os.path.sameopenfile(fp1, fp2) 判断fp1和fp2是否指向同一文件
os.path.samestat(stat1, stat2) 判断stat tuple stat1和stat2是否指向同一个文件
os.path.split(path) 把路径分割成 dirname 和 basename,返回一个元组
os.path.splitdrive(path) 一般用在 windows 下,返回驱动器名和路径组成的元组
os.path.splitext(path) 分割路径,返回路径名和文件扩展名的元组
os.path.splitunc(path) 把路径分割为加载点与文件
os.path.walk(path, visit, arg) 遍历path,进入每个目录都调用visit函数,visit函数必须有3个参数(arg, dirname, names),dirname表示当前目录的目录名,names代表当前目录下的所有文件名,args则为walk的第三个参数
os.path.supports_unicode_filenames 设置是否支持unicode路径名

实现代码
import os
def rename(path):
    i = 0
    '该文件夹下所有的文件(包括文件夹)'
    FileList = os.listdir(path)
    '遍历所有文件'
    for files in FileList:
        '原来的文件路径'
        oldDirPath = os.path.join(path, files)
        '如果是文件夹则递归调用'
        if os.path.isdir(oldDirPath):
            rename(oldDirPath)
        '文件名'
        fileName = os.path.splitext(files)[0]
        '文件扩展名'
        fileType = os.path.splitext(files)[1]
        '新的文件路径'
        newDirPath = os.path.join(path, str(i) + fileType)
        '重命名'
        os.rename(oldDirPath, newDirPath)
        i += 1


path = 'C:\\Users\Administrator\Desktop\AssetScan\\vuln'
rename(path)

方式二:
import os
path = 'C:\\Users\Administrator\Desktop\AssetScan\\vuln'
files = os.listdir(path)
for i, file in enumerate(files):
    NewName = os.path.join(path, "AssetScan_"+file)
    OldName = os.path.join(path, file)
    os.rename(OldName, NewName)

注:带有注释的问价和输出文件存在如下:
在这里插入图片描述

Python 字符串指定位置替换字符

指定位置替换字符
def replace_char(old_string, char, index):
    '''
    字符串按索引位置替换字符
    '''
    old_string = str(old_string)
    # 新的字符串 = 老字符串[:要替换的索引位置] + 替换成的目标字符 + 老字符串[要替换的索引位置+1:]
    new_string = old_string[:index] + char + old_string[index+1:]
    return new_string
指定位置添加字符
def add_char(old_string, char, index):
    '''
    将字符串按索引位置添加字符
    '''
    old_string = str(old_string)
    # 新的字符串 = 老字符串[:要替换的索引位置] + 替换成的目标字符 + 老字符串[要替换的索引位置+1:]
    new_string = old_string[:index] + char + old_string[index:]
    return new_string

文件复制

import shutil
argetdir_path = 'D:\\Python\\code\\PyQt\\1_study.py'
Targetfile_path = 'D:\\Python\\code\\2_study.py'
shutil.copyfile(argetdir_path, Targetfile_path)

上面的代码是说把路径为D:\Python\code\PyQt\1_study.py的文件1_study.py复制到D:\Python\code\2_study.py的路径下面去,复制过来的文件叫2_study.py
即shutil.copy(文件的路径,待移动到的目录)

猜你喜欢

转载自blog.csdn.net/lockhou/article/details/113834988