专业编程基础技术教程

网站首页 > 基础教程 正文

[python省时间]处理文档,包括批量查找,替换,

ccvgpt 2024-07-19 12:52:06 基础教程 15 ℃

1、批量查找替换

# -*- coding: utf-8 -*-
import os
import re
# path=os.getcwd()

str_old = 'insert'
str_new = 'frs.event.queue'
file_formate = 'init.sql'
file_sql=open(r'F:\bak\init_all.sql', 'r+', encoding='utf-8')
def replace_txt(path):
    if path.find(file_formate) == len(path) - len(file_formate):

        with open(path, 'r+', encoding='utf-8') as file:
            str = file.read()
            if str.find(str_old) > 0:
                print(path)
                str = str.replace(str_old, str_new)
                print(str)
                file.seek(0, 0)
                file.write(str)
                # file.close()
# replace_txt(r'D:\python\workspace\tools\util\txt12\test.txt.py')
def find_txt(path):
    with open(path, 'r+', encoding='utf-8') as file:
        i=0
        while True:
            line = file.readline()
            i=i+1
            if not line:
                break
            else:
                try:
                    str_line = str(line)
                    # if path.find(str_old) > 0:
                    if str_line.find(str_old) >=0:

                        print(str_line)
                        break
                except:
                    print(str(line))

2、如果不知道文件是否utf-8

def find_txt_no_formate(path):
    if file_formate !='':
        if path.find(file_formate) == len(path) - len(file_formate):
            print(path)
            with open(path, 'r+', encoding='utf-8') as file:
                str = file.read()
                file_sql.write('\n--------------------------------')
                file_sql.write(path)
                file_sql.write(str)
            # find_txt(path)
    else:
        find_txt(path)

3、列出所有文件

def list_all_file(rootdir):
    files = []
    list = os.listdir(rootdir)
    for i in range(0, len(list)):
        path = os.path.join(rootdir, list[i])
        if os.path.isdir(path):
            files.extend(list_all_file(path))
        if os.path.isfile(path):
            files.append(path)
            try:
                find_txt_no_formate(path)
            except:
                print("e")
    return files

Tags:

最近发表
标签列表