ファイルの名前変更と移動

最近実験を終えましたが、段階的に行われたため、結果は2つのフォルダーに保存されます。1つのフォルダーに結果の番号を付け直して、結果が保存される別のファイルにコピーしたいと思います。

コード

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)はリストを返します(複数のパス)、すべてのパスで共有される最長のパス
os.path.dirname(path)はファイルパスを返します
os.path.exists(path)パスが存在する場合はTrueを返し、パスが存在しない場合はFalseを返します。
os.path.lexistsは、パスが存在する場合はTrueを返し、パスが破損している場合はTrueを返します
。os.path.expanduser(path)パス含まれる「」および「 user」をユーザーディレクトリ
os.path.expandvarsに変換します。(パス)環境変数に応じてパス内の「name」、「name」、「」をの値に置き換えます。n a m e "および" {name} "
os.path.getatime(path)は、最終アクセス時刻(浮動小数点の秒数
)を返します。os.path.getmtime(path)は、最終ファイル変更時刻を返します
。os.path.getctime (パス)は、ファイルパスの作成時刻を返し
、エラーを返し、os.path.getsize(パス)ファイルが存在しない場合、ファイルのサイズを返しを
os.path.isabs(パス)が絶対パスであるかどうかを判断し
、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)パスの大文字と小文字を変換し
ますos.path.normpath(path)パス文字列形式を標準化します
os.path.realpath(path)パスの実際のパスを返します
os.path.relpath(path [、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)パスをトラバースし、それぞれを入力します。すべてのディレクトリはvisit関数を呼び出します。visit関数には3つのパラメータ(arg、dirname、names)が必要です。dirnameは現在のディレクトリのディレクトリ名を表し、namesは現在のすべてのファイル名を表しますディレクトリ、およびargsはwalkの3番目のパラメーター
osです。path.supports_unicode_filenamesユニコードパス名をサポートするかどうかを設定します

実装コード
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