1. 程式人生 > >file檔案的搜尋、內容替換

file檔案的搜尋、內容替換

指定一種字尾:


import os
import os.path

ls = []

def getAppointFile(path, ls, hz):
    fileList = os.listdir(path)
    try:
        for tmp in fileList:
            pathTmp = os.path.join(path, tmp)
            if True==os.path.isdir(pathTmp):
                getAppointFile(pathTmp, ls, hz)
            elif
pathTmp[pathTmp.rfind('.') + 1:].upper() == hz.upper(): ls.append(pathTmp) except PermissionError: pass def main(): while True: path = input('輸入指定路徑: ').strip() hz = input('輸入相同字尾: ').strip() if os.path.isdir(path) == True: break
getAppointFile(path, ls, hz) for lss in ls: print(lss) print(len(ls)) main()

多個字尾檔案:

import os

def search_file(start_dir, target) :
    os.chdir(start_dir)

    for each_file in os.listdir(os.curdir) :
        ext = os.path.splitext(each_file)[1]
        if ext in target :
            vedio_list.append(os.getcwd() + os.sep + each_file + os.linesep) 
        if
os.path.isdir(each_file) : search_file(each_file, target) # 遞迴呼叫 os.chdir(os.pardir) # 遞迴呼叫後切記返回上一層目錄 start_dir = input('請輸入待查詢的初始目錄:') program_dir = os.getcwd() target = ['.mp4', '.avi', '.rmvb'] vedio_list = [] search_file(start_dir, target) f = open(program_dir + os.sep + 'vedioList.txt', 'w') f.writelines(vedio_list) f.close()

獲取檔案字尾:

def getfile_fix(filename):
    return filename[filename.rfind('.') + 1:]
print(getfile_fix('runoob.txt'))

指定檔案中的內容替換:

def file_replace(file_name, rep_word, new_word):
    f_read = open(file_name)

    content = []
    count = 0

    for eachline in f_read:
        if rep_word in eachline:
            count = count+eachline.count(rep_word)
            eachline = eachline.replace(rep_word, new_word)
        content.append(eachline)    

    decide = input('\n檔案 %s 中共有%s個【%s】\n您確定要把所有的【%s】替換為【%s】嗎?\n【YES/NO】:' \
                   % (file_name, count, rep_word, rep_word, new_word))

    if decide in ['YES', 'Yes', 'yes']:
        f_write = open(file_name, 'w')
        f_write.writelines(content)
        f_write.close()

    f_read.close()


file_name = input('請輸入檔名:')
rep_word = input('請輸入需要替換的單詞或字元:')
new_word = input('請輸入新的單詞或字元:')
file_replace(file_name, rep_word, new_word)