修改文件名字的一个python例子


# coding=utf-8
import os,sys
import shutil
import struct

file_list = []

def listdir(folder, file_list):
    fileNum = 0
    new_file_list = os.listdir(folder) 
    for line in new_file_list:
        #print line
        filepath = os.path.join(folder,line)
        if os.path.isfile(filepath):
            print line
            file_list.append(line)
            fileNum = fileNum + 1
            #if fileNum > 10:
            #   return


#change .jpg.txt to .txt
def ChangeFileName(folder, file_list):
    for file_line in file_list:
        old_file_name = file_line
        new_file_name = file_line.replace(".jpg.txt", ".txt")
        print "new: " + new_file_name
        print "old: " + old_file_name
        if new_file_name != old_file_name:
            print "file_name:" + old_file_name
            print "new_file_name:" + new_file_name
            os.rename(os.path.join(folder, file_line), os.path.join(folder, new_file_name))

folder = sys.argv[1]
print folder
listdir(folder, file_list)
ChangeFileName(folder, file_list)

#python this folder

 

copy 未存在的文件到一个新的文件夹中

# coding=utf-8
import os,sys
import shutil
import struct
from shutil import copyfile
import re


def listdir(folder, file_list):
    fileNum = 0
    jpg_file_pattern = re.compile(r'.*\.(jpg|JPG)$')
    new_file_list = os.listdir(folder) 
    for line in new_file_list:
        #print line
        match = jpg_file_pattern.match(line)
        if match:
            filepath = os.path.join(folder,line)
            if os.path.isfile(filepath):
                print "jpg file: " + line
                file_list.append(line)
                fileNum = fileNum + 1
                #if fileNum > 10:
                #   return

#get new jpg files to floder_notExist
def GetNotExistFiles(folder, folder_exist, folder_notExist):
    file_list = []
    listdir(folder, file_list)
    for file_name in file_list:
        if os.path.exists(os.path.join(folder_exist, file_name)):
            print "file exist: " + file_name
        else:
            textFile = file_name.replace(".jpg", ".txt")
            copyfile(os.path.join(folder, file_name), os.path.join(folder_notExist, file_name))

            if os.path.exists(os.path.join(folder, textFile)):
                copyfile(os.path.join(folder, textFile), os.path.join(folder_notExist, textFile))

folder = "G:\\a\\"
folder_exist = "G:\\b\\"
folder_notExist = "G:\\c\\"

GetNotExistFiles(folder, folder_exist, folder_notExist)
#python this

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM