python获取文件夹名称、文件名、去除后缀的文件名、文件改名等

当前目录下所有文件夹下的文件名(不带后缀)写入对应txt文件(以文件夹命名)中
重命名文件
  1. getfiledata.py
# 当前目录下所有文件夹下的文件名(不带后缀)写入对应txt文件(以文件夹命名)中
import os

# 如果文件夹不存在创建文件夹
def Makedir(path):
    folder = os.path.exists(path)
    if (not folder):
        os.makedirs(path)

# 利用os.listdir()、os.walk()获取文件夹和文件名
def GetFileName(fileDir, outDir):
    list_name = []
    Makedir(outDir)
    for dir in os.listdir(fileDir):  # 获取当前目录下所有文件夹和文件(不带后缀)的名称
        filePath = os.path.join(fileDir, dir)  # 得到文件夹和文件的完整路径
        if os.path.isdir(filePath) and not (filePath == outDir):
            txt = outDir + dir + ".txt"
            # 获取根目录路径、子目录路径,根目录和子目录下所有文件名
            for root, subDir, files in os.walk(filePath):
                for fileName in files:
                    f = open(txt, 'a')  # 以追加方式打开文件
                    fileName = os.path.splitext(fileName)[0] + '\n'  # 分割,不带后缀名
                    f.write(fileName)
                    f.close()

def main():
    fileDir = "H:\\resultdata"  # 输入文件夹路径
    outDir = "H:\\resultdata\\FileData\\"
    files = GetFileData(fileDir, outDir)

# 判断是否是程序主入口而已,如果是程序主入口,则代码块执行,否则代码块不执行
# 主要用于别人调用此代码时,不要进入该代码的入口
if __name__ == "__main__":
    main()

  1. single_renamefile.py
import os

# 获取所有.mp4文件名称,不带后缀
def GetVideoName(dir):
    listName = []
    for fileName in os.listdir(dir):
        if os.path.splitext(fileName)[1] == '.mp4':
            fileName = os.path.splitext(fileName)[0]
            listName.append(fileName)
    return listName

# 获取所有.txt文件名称,不要后缀
def GetTxtName(dir):
    listName = []
    for fileName in os.listdir(dir):  
        if os.path.splitext(fileName)[1] == '.txt':
            fileName = os.path.splitext(fileName)[0]
            listName.append(fileName)
    return listName


def IsPart(frames, video):
    length = len(frames)
    for i in range(length):
        if video == frames[i]:
            return True
        else:
            continue
    return False

 # 按行获取txt文件内容
def ReadVideoInfo(path):  
    f = open(path, 'r')
    fileContents = []
    for fileContent in f.readlines(): # 获取所有行
        fileContent = fileContent.strip("\n")  # 去掉换行符
        fileContents.append(fileContent)  # 每一个视频场景对应的片段帧
    return fileContents


def ReadLabel(labelFile):
    # 获取标签内容
    f = open(labelFile, 'r')
    labelContents = []
    for line in f.readlines():
        labelContents.append(line)
    return labelContents


# 全局变量的定义
time_9 = 0
time_9_11 = 0
time_11_13 = 0
time_13_15 = 0
time_15_17 = 0
time_17 = 0


def GetTimeNum(string):
    strTmp = string.split('_')
    strTmp = strTmp[1]
    number = int(strTmp)

    # 全局变量使用前,要用global
    global time_9
    global time_9_11
    global time_11_13
    global time_13_15
    global time_15_17
    global time_17

    if number < 900:
        time_9 += 1
    elif number >= 900 and number < 1100:
        time_9_11 += 1
    elif number >= 1100 and number < 1300:
        time_11_13 += 1
    elif number >= 1300 and number < 1500:
        time_13_15 += 1
    elif number >= 1500 and number < 1700:
        time_15_17 += 1
    else:
        time_17 += 1

# 文件改名,os.rename()
def RenameFile(videoInfoDir, videoDir, labelFile):
    videosName = GetVideoName(videoDir)  # 获取待改名视频名称
    videoInfoList = GetTxtName(videoInfoDir)  # 视频场景的文件名列表

    labelContents = ReadLabel(labelFile)

    videosNameLen = len(videosName)

    for i in range(videosNameLen):  # 每个视频和所有场景对比

        for videoInfo in videoInfoList:
            path = videoInfoDir + "\\" + videoInfo + '.txt'
            fileContents = ReadVideoInfo(path)  # 当前场景的视频信息
            # 该视频文件属于该场景
            if IsPart(fileContents, videosName[i]):
                src = videoDir + '\\' + videosName[i] + '.mp4'
                dst = videoDir + '\\' + videoInfo + \
                    '_' + videosName[i] + '.mp4'
                os.rename(src, dst)
                labelLine = labelContents[i]  # 标签每行内容

                # labelLine.split(',')
                modiLine = videoInfo + '_' + labelLine

                GetTimeNum(modiLine)

                labelF = open(videoDir+'\\'+'newlabel.txt', 'a')
                labelF.write(modiLine)
                labelF.close()
                break
            # 对比完毕,找不到对应的场景,2017_05_04A
            else:
                if videoInfo == videoInfoList[len(videoInfoList) - 1]:
                    src = videoDir + '\\' + videosName[i] + '.mp4'
                    dst = videoDir + '\\' + '20170504_1300_A' + \
                        '_' + videosName[i] + '.mp4'
                    os.rename(src, dst)

                    labelLine = labelContents[i]  # 标签每行内容
                    # labelLine.split(',')
                    modiLine = '20170504_1300_A' + '_' + labelLine

                    GetTimeNum(modiLine)

                    labelF = open(videoDir+'\\'+'newlabel.txt', 'a')
                    labelF.write(modiLine)
                    labelF.close()


def main():
    videoDir = "H:\\Video_selected\\single"
    labelFile = "H:\\Video_selected\\single\\label.txt"
    videoInfoDir = "H:\\Video_selected\\FileData"
    RenameFile(videoInfoDir, videoDir, labelFile)
    print(time_9,
          time_9_11,
          time_11_13,
          time_13_15,
          time_15_17,
          time_17)


if __name__ == "__main__":
    main()

  1. mul_renamefile.py
import os
def GetVideoName(dir):
    listName = []
    for fileName in os.listdir(dir):  # 获取所有.mp4文件名称
        if os.path.splitext(fileName)[1] == '.mp4':
            fileName = os.path.splitext(fileName)[0]
            listName.append(fileName)
    return listName

def GetTxtName(dir):
    listName = []
    for fileName in os.listdir(dir):  # 获取所有.txt文件名称
        if os.path.splitext(fileName)[1] == '.txt':
            fileName = os.path.splitext(fileName)[0]
            listName.append(fileName)
    return listName

def IsPart(frames, video):
    length = len(frames)
    for i in range(length):
        if video == frames[i]:
            return True
        else:
            continue
    return False

def ReadVideoInfo(path):
   # 获取txt文件内容
    f = open(path, 'r')
    fileContents = []
    for fileContent in f.readlines():
        fileContent = fileContent.strip("\n")  # 去掉换行符
        fileContents.append(fileContent)  # 每一个视频场景对应的片段帧
    return fileContents

def ReadLabel(labelFile):
    # 获取标签内容
    f = open(labelFile, 'r')
    labelContents = []
    for line in f.readlines():
        labelContents.append(line)
    return labelContents

time_9 = 0
time_9_11 = 0
time_11_13 = 0
time_13_15 = 0
time_15_17 = 0
time_17 = 0

def GetTimeNum(string):
    strTmp = string.split('_')
    strTmp = strTmp[1]
    number = int(strTmp)

    global time_9
    global time_9_11
    global time_11_13
    global time_13_15
    global time_15_17
    global time_17

    if number < 900:
        time_9 += 1
    elif number >= 900 and number < 1100:
        time_9_11 += 1
    elif number >= 1100 and number < 1300:
        time_11_13 += 1
    elif number >= 1300 and number < 1500:
        time_13_15 += 1
    elif number >= 1500 and number < 1700:
        time_15_17 += 1
    else:
        time_17 += 1

def RenameFile(videoInfoDir, videoDir, labelFile):
    videosName = GetVideoName(videoDir)  # 获取待改名视频名称
    videosNameLen = len(videosName)
    totalVideoName = []
    for i in range(videosNameLen):
        tmp = videosName[i].split('_')
        tmp = tmp[0] + '_' + tmp[1]
        totalVideoName.append(tmp)

    videoInfoList = GetTxtName(videoInfoDir)  # 视频场景的文件名列表

    labelContents = ReadLabel(labelFile)

    for i in range(videosNameLen):  # 每个视频和所有场景对比

        for videoInfo in videoInfoList:
            path = videoInfoDir + "\\" + videoInfo + '.txt'
            fileContents = ReadVideoInfo(path)  # 当前场景的视频信息
            # 该视频文件属于该场景
            if IsPart(fileContents, totalVideoName[i]):
                src = videoDir + '\\' + videosName[i] + '.mp4'
                dst = videoDir + '\\' + videoInfo + \
                    '_' + videosName[i] + '.mp4'
                os.rename(src, dst)
                labelLine = labelContents[i]  # 标签每行内容
                # labelLine.split(',')
                modiLine = videoInfo + '_' + labelLine

                GetTimeNum(modiLine)

                labelF = open(videoDir+'\\'+'newlabel.txt', 'a')
                labelF.write(modiLine)
                labelF.close()
                break
            # 对比完毕,找不到对应的场景,2017_05_04A
            else:
                if videoInfo == videoInfoList[len(videoInfoList) - 1]:
                    src = videoDir + '\\' + videosName[i] + '.mp4'
                    dst = videoDir + '\\' + '20170504_1300_A' + \
                        '_' + videosName[i] + '.mp4'
                    os.rename(src, dst)

                    labelLine = labelContents[i]  # 标签每行内容
                    # labelLine.split(',')
                    modiLine = '20170504_1300_A' + '_' + labelLine

                    GetTimeNum(modiLine)

                    labelF = open(videoDir+'\\'+'newlabel.txt', 'a')
                    labelF.write(modiLine)
                    labelF.close()


def main():
    videoDir = "H:\\Video_selected\\multiple"
    labelFile = "H:\\Video_selected\\multiple\\label.txt"
    videoInfoDir = "H:\\Video_selected\\FileData"
    RenameFile(videoInfoDir, videoDir, labelFile)
    print(time_9,
          time_9_11,
          time_11_13,
          time_13_15,
          time_15_17,
          time_17)
if __name__ == "__main__":
	main()

你可能感兴趣的:(python)