Python - 每次出现特定字符串时将文件拆分为多个文件

我有一个文件,其中包含多个存储过程,如下所示。


--

-- Name: abc(character varying); Type: FUNCTION; Schema: schema_name; Owner: -

--

CREATE FUNCTION schema_name.abc(schema_name character varying) RETURNS opaque

    LANGUAGE plpgsql

    AS '54:-1', $$

    

DECLARE

 a  INT:= 0;

 b  INT:= 0;


BEGIN 

        

 

 END;


$$;



--

-- Name: bcd(); Type: FUNCTION; Schema: schema_name; Owner: -

--


CREATE FUNCTION schema_name.bcd() RETURNS opaque

    LANGUAGE plpgsql

    AS '-1', $$         


DECLARE

 a  INT:= 0;

 b  INT:= 0;


BEGIN 

    

 

 END;

    $$;



--

-- Name: cde(); Type: FUNCTION; Schema: schema_name; Owner: -

--


CREATE FUNCTION schema_name.cde() RETURNS opaque

    LANGUAGE plpgsql

    AS '-1', $$         


DECLARE

 a  INT:= 0;

 b  INT:= 0;


BEGIN 

    


 

 END;

    $$;

我需要把它分成每个以


--

-- Name:

此外,各个文件应以架构名称命名。在这种情况下,文件名应为 abc.sql、bcd.sql、cde.sql..


到目前为止我试过这个


token = 'CREATE FUNCTION'

chunks = []

current_chunk = []


for line in open('procedures.txt'):

   if line.startswith(token) and current_chunk: 

      chunks.append(current_chunk[:])

      current_chunk = []

   current_chunk.append(line)

   print (current_chunk)


chunks.append(current_chunk) 


撒科打诨
浏览 102回答 1
1回答

烙印99

尝试这个:import ospath = r"D:\test"token = '-- Name: 'chunks = {}current_chunk = []with open (os.path.join(path, "test.txt"), "r") as myfile:    data=myfile.readlines()for line in data:    if line.startswith(token):        start = line.find("token")+len(token)        end = line.find("(")        schema_name = line[start:end].strip()                current_chunk = []        current_chunk.append(line)        chunks[schema_name] = current_chunk    else:        current_chunk.append(line)print (chunks)for name, storage in chunks.items():    print(name)    with open(os.path.join(path, name + '.sql'), 'w') as file:        file.write(" ".join(storage))        file.close()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python